How do I disable touchableOpacity? - react-native

I am making an appointment app, I have 6 time slots on a given day. The selected slots are stored into a const called "notAvailableSlots" as soon as the component loads. How do I disable the touchableOpacity if "notAvailableSlots" has corresponding values in it, meaning someone has clicked one of the 6 slots already? I know it takes a boolean, but stuck thinking what value to pass...
const availableHours = {
timeSlots: {
slot1: "2:00pm to 2:30pm",
slot2: "2:30pm to 3:00pm",
slot3: "3:00pm to 3:30pm",
slot4: "3:30pm to 4:00pm",
slot5: "4:00pm to 4:30pm",
slot6: "4:30pm to 5:00pm"
}
};
class Appointment extends Component {
constructor(props) {
super(props);
this.state = {
datePicker: false,
date: new Date()
};
}
componentDidMount() {
this.props.fetchDataFromHeroku();
}
render() {
const availability = availableHours.timeSlots;
const notAvailableSlots = this.props.date
.filter(date => {
const month = new Date(date.date).getMonth();
const day = new Date(date.date).getDate();
const year = new Date(date.date).getFullYear();
return (
month === this.state.date.getMonth() &&
day === this.state.date.getDate() &&
year === this.state.date.getFullYear()
);
})
.map(date => date.time_slot);
// console.log(this.state.date);
console.log("not available: ", notAvailableSlots);
return (
<View style={styles.container}>
<Text style={{ backgroundColor: "#00CED1", height: 35 }}>
Hi! Please click on "calendar" to setup an appointment
</Text>
<View>
<Button
style={styles.buttonOne}
title="Make an appointment"
onPress={() => {
const { action, year, month, day } = DatePickerAndroid.open({
date: new Date()
}).then(response => {
this.setState({
datePicker: true,
date: new Date(response.year, response.month, response.day)
});
response.month += 1;
console.log("date", response);
});
}}
/>
{this.state.datePicker
? Object.keys(availability).map((time, i) => {
// console.log(time); this returns slots 1 thru 6
return (
<View key={i} style={styles.slotButton}>
<TouchableOpacity
disabled={true}
onPress={() =>
this.props.addTimeSlotToDatabase(
time,
this.props.user.id,
this.state.date
)
}
>
<Text style={{ alignItems: "center" }}>
{availability[time]}
</Text>
</TouchableOpacity>
</View>
);
})
: null}
</View>
</View>
);
}
}

Simply put the value in the state.
constructor(props) {
super(props);
this.state = {
disabled: false
};
}
render() {
return(
<TouchableOpacity disabled={this.state.disabled}>
<Text>Click</Text>
</TouchableOpacity>
)
}

Sometimes I do like this
import { TouchableOpacity, View } from 'react-native';
const MainView = isDisabled ? View : TouchableOpacity;
return (
<MainView onPress={}>

Related

How to pass state between screens in React Native

This is screen 1, where I am supposed to be passing the state for button text.
export class EditProfile extends Component {
constructor(props) {
super(props);
this.navigateToName = this.navigateToName.bind(this);
this.navigateToAboutMe = this.navigateToAboutMe.bind(this);
this.navigateToInterests = this.navigateToInterests.bind(this);
this.state = {
showing: true,
aboutUser: {
buttonText: "hey",
showing: false,
},
};
}
navigateToName = () => {
this.props.navigation.navigate("CreateProfile", {
showing: false,
});
};
navigateToAboutMe = () => {
this.props.navigation.navigate("AboutUser", {
aboutUser: this.state.aboutUser,
});
};
navigateToInterests = () => {
this.props.navigation.navigate("Interests", { showing: false });
};
render() {
return (
<View>
<View style={ProfileEditStyle.justifyImage}>
<Image
style={ProfileEditStyle.image}
source={require("../../Graphics/jessica_alba.jpg")}
/>
</View>
<View>
<Text style={ProfileEditStyle.basictext}>Basic Info</Text>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text} onPress={this.navigateToName}>
Edit Name
</Text>
</TouchableOpacity>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text}>Edit Photo</Text>
</TouchableOpacity>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text}>Edit Location</Text>
</TouchableOpacity>
<TouchableOpacity
style={ProfileEditStyle.buttons}
onPress={this.navigateToAboutMe}
>
<Text style={ProfileEditStyle.text}>Edit About Me</Text>
</TouchableOpacity>
<TouchableOpacity
style={ProfileEditStyle.buttons}
onPress={this.navigateToInterests}
>
<Text style={ProfileEditStyle.text}>Edit Interests</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
export default EditProfile;
This is screen 2, where I want the state for the buttonText to change on the continue button component.
export class AboutUser extends Component {
constructor(props) {
super(props);
this.navigatToInterests = this.navigatToInterests.bind(this);
this.checkEntry = this.checkEntry.bind(this);
var params = props.navigation.state.params.aboutUser;
this.state = {
value: "",
};
}
<ContinueButton
text={this.props.route.params.aboutUser.buttonText}
color="#ff304f"
style={CreateAboutMe.centerButton}
onPress={this.navigatToInterests}
/>
I am trying to do conditional rendering for the continue button component. When its on one screen I want it to say "continue" and when its on another route I want it to say " Save and Go Back". However when I try to change the state between screens for some reason I either get a params error or the state doesn't change.
Get parameter from previous screen :
constructor(){
const isShowBtn = this.props.navigation.getParam("showing");
this.state = {
value: isShowBtn
}
}

How to null check and navigate to new screen on click submit when textinput and submit button both are in different js files in react native?

render(){
return (
<ImageBackground
source={require('../images/back02.png')}
style={styles.bgscreen}
>
<KeyboardAvoidingView behavior='position'>
<Image
style={styles.headImage}
source={require('../images/login_img.png')}
/>
<ImgBack/>
</KeyboardAvoidingView>
<BottomButton navigation={this.props.navigation} />
</ImageBackground>
);}
}
ImgBack contains username and password textinput.
BottomButton contains the submit button
I want to navigate to new activity when submit button clicked. navigation to new screen is working perfectly but before navigating i want to null check the TextInput which are on
I am new to React-Native. Complete Beginner here. I want even know what to do. Help.
ImgBack.js file
class imgBack extends React.Component {
constructor()
{
super();
this.state = { hidePassword: true }
}
managePasswordVisibility = () =>
{
this.setState({ hidePassword: !this.state.hidePassword });
}
usernameValidate = (EnteredValue) =>{
var TextLength = EnteredValue.length.toString();
if(TextLength == 10 ){
Alert.alert("Sorry, You have reached the maximum input limit.")
}
else if(TextLength == 0){
Alert.alert("Username can't be blank")
}
}
passValidate = (EnteredValue) =>{
var TextLength = EnteredValue.length.toString();
if(TextLength == 10 ){
Alert.alert("Sorry, You have reached the maximum input limit.")
}
else if(TextLength == 0){
Alert.alert("Username can't be blank")
}
}
render(){
return (
<ImageBackground resizeMode='contain'
source={require('../images/login_back.png')}
style={{
marginHorizontal: 10,
height: 290,
padding: 30,
}}>
<View style={
styles.textInputContainer
} >
<TextInput
placeholder="Username"
underlineColorAndroid = "transparent"
placeholderTextColor="#000000"
maxLength={10}
onChangeText={ EnteredValue => this.usernameValidate(EnteredValue) }
/>
</View>
<View style = { styles.textInputContainer }>
<TextInput
onChangeText={ EnteredValue => this.passValidate(EnteredValue) }
underlineColorAndroid = "transparent"
secureTextEntry = { this.state.hidePassword }
placeholder="Password"
placeholderTextColor="#000"
/>
<TouchableOpacity style = { styles.visibilityBtn } onPress = { this.managePasswordVisibility }>
<Image source = { ( this.state.hidePassword ) ? require('../images/eye_close_icon.imageset/eye_close_icon.png') : require('../images/eye_icon.imageset/eye_icon.png') } style = { styles.btnImage } />
</TouchableOpacity>
</View>
</ImageBackground>
)
}
} ```
**Bottombutton File**
class bottomButon extends Component {
render(){
return (
<ImageBackground
style={{ height: 80, marginLeft: '20%', marginTop: 10 }}
resizeMode={'center'}
source={require('../images/btn_back.png')} >
<TouchableOpacity
onPress={ this.login } >
<Text style={{ textAlign: 'center', marginTop: 25 }}>Submit & SYNC</Text>
</TouchableOpacity>
</ImageBackground>
)
} }
export default bottomButon; ```
solution:
constructor(props) {
super(props);
this.state = {
hidePassword: true,
username: '',
password: '',
};
}
validUserPass = async () => {
try {
if (this.state.username === '') {
Alert.alert('Username is required !');
} else if (this.state.password === '') {
Alert.alert('Password is required !');
} else {
this.props.navigation.navigate('selectEmoji');
}
} catch (error) {
console.warn(error);
}
};
it helped me solve my issue.

Is there a way to "fade in" items in flatlist?

I'm setting up a component that render a flatlist and I'm trying to make the flatlist items "fade in" animation For a more impressive display
This is a component for render search suggestions that show items
import React, { Component } from 'react'
import { View, Text, TextInput, FlatList, Image, TouchableOpacity } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { Button } from '../../components'
import Style from './style'
import I18n from '../../i18n'
import Icon from 'react-native-vector-icons/MaterialIcons'
import Api from '../../utils/Api'
import _ from 'lodash'
let mounted = false
#inject('UserStore', 'NavigationStore')
#observer
class SearchProducts extends Component {
constructor(props) {
super(props)
this.state = {
searchAutoComplete: [],
showAutoComplete: false,
currentSearch: '',
searchTimeoutId: null,
}
this.autoCompleteTimeout = null
this.storedResults = []
}
componentWillMount() {
mounted = true
}
componentWillUnmount() {
mounted = false
clearTimeout(this.autoCompleteTimeout)
}
_renderCategory = ({ item }) => {
return (
<View style={Style.featuredView}>
<Image source={item.image} style={Style.featuredImage} />
<Text style={{ textAlign: 'center', color: '#9B999A' }}>{item.title}</Text>
</View>
)
}
_renderSuggestion = ({ item, index }) => {
const splittedName = item.split(' ')
let splittedSearch = this.state.currentSearch.toUpperCase().split(' ')
splittedSearch = splittedSearch.map(x => x.trim()).filter(x => x.length > 1)
let suggestion = []
if (splittedSearch.length == 0) {
suggestion = splittedName.map((word, index) => <Text key={index}>{word} </Text>)
} else {
let highlightedWords = []
splittedName.forEach((word, index) =>
splittedSearch.forEach(wordFromSearch => {
const currentWord = word.toUpperCase()
const isAlreadyHighlighted = highlightedWords.includes(currentWord)
if ((currentWord.includes(wordFromSearch.toUpperCase()) && this.state.currentSearch.length > 0) || isAlreadyHighlighted) {
let v = (
<Text key={index} style={{ color: '#2eb872' }}>
{word}{' '}
</Text>
)
if (!isAlreadyHighlighted) {
highlightedWords.push(currentWord)
}
suggestion[index] = v
} else {
let v = <Text key={index}>{word} </Text>
suggestion[index] = v
}
})
)
}
return (
<TouchableOpacity
style={Style.suggestionView}
onPress={() => {
this.props.UserStore.addRecentSearch(item)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: item } })
this.autoCompleteTimeout = setTimeout(() => {
if (mounted) this.setState({ showAutoComplete: false })
}, 400)
}}
>
<Icon name='search' size={20} style={{}} />
<Text style={{ marginLeft: 20, textAlign: 'left', color: '#9B999A' }}>{suggestion}</Text>
</TouchableOpacity>
)
}
getSuggestions = async currentSearch => {
try {
const response = await Api.serachOutoCompleate(currentSearch)
let searchAutoComplete = response.suggestions.products.map(product => product.product_title)
response.suggestions.categories.forEach(categories => searchAutoComplete.push(categories))
response.suggestions.warehouses.forEach(warehouse => searchAutoComplete.push(warehouse.warehouse_name))
response.suggestions.upcs.forEach(upcs => searchAutoComplete.push(upcs.product_title))
response.suggestions.tags.forEach(tags => searchAutoComplete.push(tags.product_title))
this.storedResults[currentSearch] = searchAutoComplete
if (mounted && currentSearch && searchAutoComplete) this.setState({ currentSearch: currentSearch, searchAutoComplete: searchAutoComplete })
else this.setState({ currentSearch: currentSearch })
} catch (error) {
console.log(error)
}
}
_onSearchChange = _.debounce(currentSearch => {
if (currentSearch === '') {
this.setState({ filter: [], currentSearch })
} else {
if (this.storedResults[currentSearch]) {
this.setState({ currentSearch })
let searchAutoComplete = this.storedResults[currentSearch]
if (mounted && currentSearch && searchAutoComplete) this.setState({ searchAutoComplete })
} else {
this.getSuggestions(currentSearch)
}
}
}, 250)
render() {
I18n.locale = this.props.UserStore.user.lang
const recent = this.props.UserStore.RecentSearches
return (
<View style={Style.container}>
<View style={Style.search_container}>
<TextInput
style={Style.search_input}
underlineColorAndroid='transparent'
placeholder={I18n.t('search_products')}
returnKeyType='search'
autoCorrect={false}
onChangeText={this._onSearchChange}
onFocus={() => this.setState({ showAutoComplete: true })}
onSubmitEditing={event => {
if (event.nativeEvent.text.length) this.props.UserStore.addRecentSearch(event.nativeEvent.text)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: event.nativeEvent.text } })
}}
onKeyPress={() => this.suggestionTimeout && clearTimeout(this.suggestionTimeout)}
blurOnSubmit
/>
</View>
{this.state.currentSearch.length > 0 && this.state.showAutoComplete && this.state.searchAutoComplete.length > 0 ? (
<View style={{ paddingVertical: 10 }}>
<FlatList initialNumToRender={20} data={this.state.searchAutoComplete} keyExtractor={(item, index) => item.toString()} renderItem={this._renderSuggestion} keyboardShouldPersistTaps='always' />
</View>
) : (
<View>
{recent.length > 0 ? (
<View>
<View style={Style.whiteBorder} />
<View style={Style.searchHistory}>
<Text style={Style.searchHistory_header}>{I18n.t('recent_searches')}</Text>
{recent.map((title, index) => (
<Button
key={index}
style={Style.recentSearch}
onPress={() => {
this.props.UserStore.addRecentSearch(title)
this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: title } })
}}
>
<Icon name='schedule' style={Style.recentSearchIcon} />
<Text style={Style.recentSearchText}>{title}</Text>
</Button>
))}
</View>
</View>
) : null}
</View>
)}
</View>
)
}
}
export default SearchProducts
I expect the output will show fade in animation in the flatlist
and i dont know how to implement it
This can be accomplished by using the Animated api.
First import Animated from react-native, then add fade: new Animated.Value(0) to your state inside the constructor.
Now change the View that is surrounding the FlatList from this
<View style={{ paddingVertical: 10 }}>
to this
<Animated.View style={{ paddingVertical: 10, opacity: this.state.fade }}>
At last add this block to start the animation when the list mounts:
componentDidMount() {
Animated.timing(this.state.fade, {
duration: 500,
toValue: 1,
useNativeDrivers: true
}).start();
}
If you want to animate the FlatList in every time the user makes a search, you would have to move this block to another part of your program logic and remember to set the fade value back to 0 before the animation.

Expo SDK 29 FlatList onRefresh not calling

Using Expo SDK 29 for a react native application.
I would like to use a flat list component. This makes up the entirety of a SafeAreaView component. I make this point as there are lots of issues relating to a flat list inside of a scroll view which this is not.
The flat list shows a list of jobs.
I have added a jobLoading boolean to the redux state to manage when the list should show as refreshing and can confirm that this toggles as expected when firing the actions to fetch the data and the success.
When i add the props to the flat list for onRefresh and refreshing the component seems to work by showing the activity indicator in the UI but does not fire the onRefresh function. I have tried implementing the call in numerous ways but nothing happens. The result is that the activity indicator shows itself and never disappears.
As it's Expo SDK 29 the React Native version is 0.55.4
Anyone have any ideas of what to try. I've spent a couple of hours looking at this trying various things but suggestions are welcome.
Thanks in advance.
EDIT: Added the code for reference. Reducer for refreshing sets true when fetchJobs() is dispatched and false when a success or error is recieved. The console log for onRefresh never triggers.
import * as React from 'react'
import * as actions from '../../redux/actions'
import { ActivityIndicator, FlatList, KeyboardAvoidingView, Dimensions, SafeAreaView, StyleSheet, View } from 'react-native'
import { ApplicationState, JobState, Job } from '../../redux'
import { Button, Form, Input, Item, Text, Icon } from 'native-base'
import { JobListItem } from './jobListItem'
import { StateHandlerMap, compose, lifecycle, withPropsOnChange, withStateHandlers } from 'recompose'
import { connect } from 'react-redux'
interface ReduxStateProps {
jobs: JobState
refreshing: boolean
screenOrientation: string
}
interface ReduxDispatchProps {
fetchJobs: (param?: string) => any
}
export interface DataItem {
key: string
data: Job
}
interface ListProps {
jobList: DataItem[]
}
interface SearchStateProps {
timer: number | undefined
searchString: string
}
interface SearchHandlerProps extends StateHandlerMap<SearchStateProps> {
updateSearch: (searchString: string) => any
setTimer: (timer: number | undefined) => any
}
type OuterProps = {}
type InnerProps = OuterProps & ReduxStateProps & ReduxDispatchProps & ListProps & SearchStateProps & SearchHandlerProps
const enhance = compose<InnerProps, OuterProps>(
connect<ReduxStateProps, ReduxDispatchProps, OuterProps, ApplicationState>(
state => ({
jobs: state.job,
refreshing: state.jobLoading,
screenOrientation: state.screenOrientation
}),
dispatch => ({
fetchJobs: (param?: string) => dispatch(actions.jobs.request({ param }))
})
),
withPropsOnChange<ListProps, OuterProps & ReduxStateProps & ReduxDispatchProps>(
['jobs', 'screenOrientation'],
props => ({
jobList: props.jobs && Object.keys(props.jobs).map(job => ({ key: job, data: props.jobs[Number(job)] }))
})
),
withStateHandlers<SearchStateProps, SearchHandlerProps, OuterProps>(
{
timer: undefined,
searchString: ''
},
{
updateSearch: state => (searchString: string) => ({ searchString }),
setTimer: state => (timer: number | undefined) => ({ timer })
}
),
lifecycle<InnerProps, {}>({
componentDidMount() {
this.props.fetchJobs()
}
})
)
export const JobList = enhance(({ fetchJobs, jobList, refreshing, screenOrientation, searchString, setTimer, timer, updateSearch }) => {
const onSearchChange = (search: string) => {
clearTimeout(timer)
updateSearch(search)
const timing = setTimeout(() => {
fetchJobs(search)
}, 500)
setTimer(timing)
}
const onRefresh = () => {
console.log('requesting refresh')
fetchJobs()
}
return (
<SafeAreaView style={{ flex: 1}}>
<KeyboardAvoidingView style={{ flexDirection: 'row', justifyContent: 'space-evenly', paddingTop: 3, paddingRight: 3 }}>
<Form style={{ flex: 1, paddingLeft: 10, paddingRight: 10 }}>
<Item>
<Input
value={searchString}
onChangeText={(text: string) => onSearchChange(text)}
placeholder='Search'
/>
</Item>
</Form>
<Button onPress={() => {fetchJobs(); updateSearch('')}}>
<Icon name='refresh' />
</Button>
</KeyboardAvoidingView>
{refreshing &&
<View style={styles.refreshContainer}>
<Text style={{ paddingBottom: 10 }}>Fetching Data</Text>
<ActivityIndicator />
</View>
}
<FlatList
keyExtractor={item => item.key}
data={jobList}
renderItem={({ item }) =>
<JobListItem
screenOrientation={screenOrientation}
item={item}
/>
}
onRefresh={onRefresh}
refreshing={refreshing}
/>
</SafeAreaView>
)
})
const styles = StyleSheet.create({
refreshContainer: {
height: 60,
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}
})
I'm having the exact same issue and I'm using expo SDK 30. But my case is a little bit different. The onRefresh function is called everytime I pull, however if I scroll down my list, and scroll back up fast, the loading indicator shows up, but my onRefresh function is not called.
My refreshing prop is set on my reducer, and my onRefresh function dispatches an action that fetches data and set refreshing true and false.
Here is my code:
class NoticiasScreen extends Component {
static navigationOptions = {
header: <Header
title='Notícias Alego'
leftComponent={<Image source={require('../../../assets/images/play_grande.png')} style={imageStyle} resizeMode='contain'/>}
/>
}
constructor(props) {
super(props);
this.renderItem = this.renderItem.bind(this);
this.keyExtractor = this.keyExtractor.bind(this);
this.renderContent = this.renderContent.bind(this);
this.navigateToNoticias = this.navigateToNoticias.bind(this);
this.carregarMaisNoticias = this.carregarMaisNoticias.bind(this);
this.onRefresh = this.onRefresh.bind(this);
}
componentDidMount() {
this.props.carregarNoticias(this.props.pagina);
}
renderItem({item}) {
return (
<NoticiaListItem noticia={item} abrirNoticia={this.navigateToNoticias} />
);
}
keyExtractor(item) {
return item.id.toString();
}
navigateToNoticias(noticia) {
this.props.navigation.navigate('NoticiasExibir', { id: noticia.id });
}
onRefresh() {
console.log('onRfresh');
this.props.carregarNoticias(1, true);
}
carregarMaisNoticias() {
const { carregarNoticias, pagina } = this.props;
carregarNoticias(pagina + 1);
}
renderContent() {
const { noticias, carregandoNoticias, erroNoticias } = this.props;
if(noticias.length === 0 && carregandoNoticias) {
return (
<View style={styles.containerCenter}>
<ActivityIndicator size="large" color={colors.verde}/>
</View>
);
}
if(erroNoticias) {
return (
<View style={styles.containerCenter}>
<Text style={styles.message}>{erroNoticias}</Text>
<TouchableOpacity hitSlop={hitSlop15}>
<Text>Recarregar</Text>
</TouchableOpacity>
</View>
)
}
return (
[<TextInput
style={styles.textInput}
placeholder='Pesquise'
key='pesquisa'
underlineColorAndroid='transparent'
/>,
<FlatList
data={noticias}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
style={styles.list}
key='lista'
onRefresh={this.onRefresh}
refreshing={carregandoNoticias}
onEndReached={this.carregarMaisNoticias}
onEndReachedThreshold={0.1}
/>]
)
}
render() {
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
{this.renderContent()}
</View>
</SafeAreaView>
);
}
}
function mapStateToProps(state) {
return {
noticias: state.intranet.noticias,
pagina: state.intranet.pagina,
erroNoticias: state.intranet.erroNoticias,
carregandoNoticias: state.intranet.carregandoNoticias
}
}
function mapDispatchToProps(dispatch) {
return {
carregarNoticias: (pagina, recarregar) => dispatch(ActionCreator.carregarNoticias(pagina, recarregar))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NoticiasScreen);
No idea what's going on. Any help is appreciated.
EDIT:
I fixed it somehow. I added the onMomentScrollBegin prop to prevent my flatList from rendering twice on Render, and that fixed this issue.
here is what I added:
constructor(props) {
super(props);
...
this.onRefresh = this.onRefresh.bind(this);
this.onMomentumScrollBegin = this.onMomentumScrollBegin.bind(this);
this.onEndReachedCalledDuringMomentum = true; //PUT THIS HERE
}
onRefresh() {
this.props.carregarNoticias(1, true);
}
carregarMaisNoticias() {
if(!this.onEndReachedCalledDuringMomentum){
const { carregarNoticias, pagina } = this.props;
carregarNoticias(pagina + 1);
this.onEndReachedCalledDuringMomentum = true;
}
}
onMomentumScrollBegin() {
this.onEndReachedCalledDuringMomentum = false;
}
render() {
<OptimizedFlatList
data={noticias}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
style={styles.list}
key='lista'
onRefresh={this.onRefresh}
refreshing={carregandoNoticias}
onMomentumScrollBegin={this.onMomentumScrollBegin} //PUT THIS HERE
onEndReached={this.carregarMaisNoticias}
onEndReachedThreshold={0.1}
/>
}

Highlight a selected item in React-Native FlatList

I put together a simple React-native application to gets data from a remote service, loads it in a FlatList. When a user taps on an item, it should be highlighted and selection should be retained. I am sure such a trivial operation should not be difficult. I am not sure what I am missing.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
FlatList,
ActivityIndicator,
Image,
TouchableOpacity,
} from 'react-native';
export default class BasicFlatList extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false,
selectedItem:'null',
};
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const {page, seed} = this.state;
const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
this.setState({loading: true});
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: page === 1 ? res.results : [...this.state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
});
})
.catch(error => {
this.setState({error, loading: false});
});
};
onPressAction = (rowItem) => {
console.log('ListItem was selected');
console.dir(rowItem);
this.setState({
selectedItem: rowItem.id.value
});
}
renderRow = (item) => {
const isSelectedUser = this.state.selectedItem === item.id.value;
console.log(`Rendered item - ${item.id.value} for ${isSelectedUser}`);
const viewStyle = isSelectedUser ? styles.selectedButton : styles.normalButton;
return(
<TouchableOpacity style={viewStyle} onPress={() => this.onPressAction(item)} underlayColor='#dddddd'>
<View style={styles.listItemContainer}>
<View>
<Image source={{ uri: item.picture.large}} style={styles.photo} />
</View>
<View style={{flexDirection: 'column'}}>
<View style={{flexDirection: 'row', alignItems: 'flex-start',}}>
{isSelectedUser ?
<Text style={styles.selectedText}>{item.name.first} {item.name.last}</Text>
: <Text style={styles.text}>{item.name.first} {item.name.last}</Text>
}
</View>
<View style={{flexDirection: 'row', alignItems: 'flex-start',}}>
<Text style={styles.text}>{item.email}</Text>
</View>
</View>
</View>
</TouchableOpacity>
);
}
render() {
return(
<FlatList style={styles.container}
data={this.state.data}
renderItem={({ item }) => (
this.renderRow(item)
)}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
},
selectedButton: {
backgroundColor: 'lightgray',
},
normalButton: {
backgroundColor: 'white',
},
listItemContainer: {
flex: 1,
padding: 12,
flexDirection: 'row',
alignItems: 'flex-start',
},
text: {
marginLeft: 12,
fontSize: 16,
},
selectedText: {
marginLeft: 12,
fontSize: 20,
},
photo: {
height: 40,
width: 40,
borderRadius: 20,
},
});
When user taps on an item in the list, "onPress" method is invoked with the information on selected item. But the next step of highlight item in Flatlist does not happen. 'UnderlayColor' is of no help either.
Any help/advice will be much appreciated.
You can do something like:
For the renderItem, use something like a TouchableOpacity with an onPress event passing the index or id of the renderedItem;
Function to add the selected item to a state:
handleSelection = (id) => {
var selectedId = this.state.selectedId
if(selectedId === id)
this.setState({selectedItem: null})
else
this.setState({selectedItem: id})
}
handleSelectionMultiple = (id) => {
var selectedIds = [...this.state.selectedIds] // clone state
if(selectedIds.includes(id))
selectedIds = selectedIds.filter(_id => _id !== id)
else
selectedIds.push(id)
this.setState({selectedIds})
}
FlatList:
<FlatList
data={data}
extraData={
this.state.selectedId // for single item
this.state.selectedIds // for multiple items
}
renderItem={(item) =>
<TouchableOpacity
// for single item
onPress={() => this.handleSelection(item.id)}
style={item.id === this.state.selectedId ? styles.selected : null}
// for multiple items
onPress={() => this.handleSelectionMultiple(item.id)}
style={this.state.selectedIds.includes(item.id) ? styles.selected : null}
>
<Text>{item.name}</Text>
</TouchableOpacity>
}
/>
Make a style for the selected item and that's it!
In place of this.state.selectedItem and setting with/checking for a rowItem.id.value, I would recommend using a Map object with key:value pairs as shown in the RN FlatList docs example: https://facebook.github.io/react-native/docs/flatlist.html. Take a look at the js Map docs as well: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map.
The extraData prop recommended by #j.I-V will ensure re-rendering occurs when this.state.selected changes on selection.
Your onPressAction will obviously change a bit from example below depending on if you want to limit the number of selections at any given time or not allow user to toggle selection, etc.
Additionally, though not necessary by any means, I like to use another class or pure component for the renderItem component; ends up looking something like the following:
export default class BasicFlatList extends Component {
state = {
otherStateStuff: ...,
selected: (new Map(): Map<string, boolean>) //iterable object with string:boolean key:value pairs
}
onPressAction = (key: string) => {
this.setState((state) => {
//create new Map object, maintaining state immutability
const selected = new Map(state.selected);
//remove key if selected, add key if not selected
this.state.selected.has(key) ? selected.delete(key) : selected.set(key, !selected.get(key));
return {selected};
});
}
renderRow = (item) => {
return (
<RowItem
{...otherProps}
item={item}
onPressItem={this.onPressAction}
selected={!!this.state.selected.get(item.key)} />
);
}
render() {
return(
<FlatList style={styles.container}
data={this.state.data}
renderItem={({ item }) => (
this.renderRow(item)
)}
extraData={this.state}
/>
);
}
}
class RowItem extends Component {
render(){
//render styles and components conditionally using this.props.selected ? _ : _
return (
<TouchableOpacity onPress={this.props.onPressItem}>
...
</TouchableOpacity>
)
}
}
You should pass an extraData prop to your FlatList so that it will rerender your items based on your selection
Here :
<FlatList style={styles.container}
data={this.state.data}
extraData={this.state.selectedItem}
renderItem={({ item }) => (
this.renderRow(item)
)}
/>
Source : https://facebook.github.io/react-native/docs/flatlist
Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes
First
constructor() {
super();
this.state = {
selectedIds:[]
};
}
Second
handleSelectionMultiple = async (id) => {
var selectedIds = [...this.state.selectedIds] // clone state
if(selectedIds.includes(id))
selectedIds = selectedIds.filter(_id => _id !== id)
else
selectedIds.push(id)
await this.setState({selectedIds})
}
Third
<CheckBox
checked={this.state.selectedIds.includes(item.expense_detail_id) ? true : false}
onPress={()=>this.handleSelectionMultiple(item.expense_detail_id)}
/>
Finally i got the solution to my problem from the answer given by Maicon Gilton