I have some tabs. I want to change the color of the selected tab. I created a state for selected tab index which will hold the tab ID. When Tab is pressed the selected state change to the pressed tab ID. I am comparing the selected state to tab ID. If both are equal then the selected tab will have some different style.
But when state changes and condition is true, the selected tab is not changing its state. Why change in state do not trigger the comparison in the style to update the style?
<FlatList
horizontal
data={this.state.drinkgroup}
showsHorizontalScrollIndicator={false}
renderItem={({item, index}) =>
{
return <Tab
item={item}
selected={this.state.selected}
changeSelected={
() => {
this.setState({selected: item.id}, function(){ console.log(this.state.selected, item.id)
console.log(this.state.selected==item.id)
})
}}
}
}
/>
export const Tab = ({item, selected, changeSelected}) => {
return (
<TouchableOpacity
style={[styles.tabStyle, (selected==item.id)? styles.tabSelectedStyle: null]}
onPress={changeSelected}
underlayColor='#fff'
>
<Text style={{color: '#f2f2f2', textAlign: 'center', fontSize: 15}}>{item.name}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
tabStyle: {
backgroundColor: '#800080',
height: 32,
paddingRight: 15,
paddingLeft: 15
},
tabSelectedStyle: {
borderBottomColor: 'white',
borderBottomWidth: 3
}
})
By passing extraData={this.state} to FlatList
we make sure FlatList itself will re-render when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.
<FlatList
data={this.props.data}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
This is a PureComponent which means that it will not re-render if props remain shallow- equal.
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.
This includes the data prop and parent component state.
More Details :- FlatList