Reputation: 203
I want to display some items with a flatlist, when I tap on the item I want it to turn green. The issue I having is that I tap on a couple of the item and then I search for a device, for example: 112. When I remove the entry I see that the previous items are not in green anymore. Snack: https://snack.expo.io/Skhaj78WU
<FlatList
data={this.state.data}
renderItem={({ item }) => <Item item={item}/>
keyExtractor={item => item[0]}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
extraData={this.state.data}
/>
This is the Item component:
class Item extends Component{
constructor(props) {
super(props)
this.state={
currentColor:'white'
}
this.onClick = this.onClick.bind(this)
}
onClick() {
console.log(this.props.item[1].isSelected)
console.log(this.props.item[0])
this.props.item[1].isSelected = !this.props.item[1].isSelected
var color = 'white'
if (this.props.item[1].isSelected){
color='green'
}
this.setState({currentColor:color})
}
render(){
return (
<TouchableHighlight onPress={this.onClick} key={this.props.item[0]}>
<View style={[styles.item, {backgroundColor: this.state.currentColor}]}>
<Text style={styles.title}>{this.props.item[1].name}</Text>
</View>
</TouchableHighlight>
);
}
}
Upvotes: 1
Views: 36
Reputation: 2220
This line is causing your problems:
this.props.item[1].isSelected = !this.props.item[1].isSelected
Props should always be treated as read-only. The normal method of modifying a list from a list item is to pass a callback to each item and modify the list from the parent component, like this:
class Item extends Component {
constructor(props) {
super(props);
}
getColor = () => (this.props.item[1].isSelected ? 'green' : 'white');
render() {
return (
<TouchableHighlight onPress={this.props.onClick} key={this.props.item[0]}>
<View style={[styles.item, { backgroundColor: this.getColor() }]}>
<Text style={styles.title}>{this.props.item[1].name}</Text>
</View>
</TouchableHighlight>
);
}
}
toggleListItem = index => {
const { data } = this.state;
data[index][1].isSelected = !data[index][1].isSelected;
this.setState({ data });
};
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
data={this.state.data}
renderItem={({ item, index }) => (
<Item item={item} onClick={() => this.toggleListItem(index)} />
)}
keyExtractor={item => item[0]}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
extraData={this.state.data}
/>
</SafeAreaView>
);
}
Upvotes: 1