Created
January 8, 2019 16:40
-
-
Save amiralies/c25bd2b860a0bc5d22493c0eba48a0f2 to your computer and use it in GitHub Desktop.
How to use extraData prop to update your react native FlatList efficiently
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SelectableItem extends React.Component { | |
constructor() { | |
super(); | |
this.handleOnPress = this.handleOnPress.bind(this); | |
} | |
shouldComponentUpdate(nextProps) { | |
const { isSelected } = this.props; | |
return isSelected !== nextProps.isSelected; | |
} | |
handleOnPress() { | |
const { onPress } = this.props; | |
onPress(); | |
} | |
render() { | |
const { isSelected, text } = this.props; | |
const textColor = isSelected ? 'blue' : 'black'; | |
return ( | |
<TouchableOpacity onPress={this.handleOnPress}> | |
<View> | |
<Text style={{ color: textColor }}>{text}</Text> | |
</View> | |
</TouchableOpacity> | |
); | |
} | |
} | |
class SelectList extends React.Component { | |
constructor() { | |
super(); | |
this.handleOnPressItem = this.handleOnPressItem.bind(this); | |
this.state = { | |
selected: new Map(), | |
}; | |
} | |
onPressItem(id) { | |
this.setState((state) => { | |
const selected = new Map(state.selected); | |
selected.set(id, !selected.get(id)); | |
return { selected }; | |
}); | |
} | |
renderItem({ item }) { | |
const { selected } = this.state; | |
return ( | |
<SelectableItem | |
id={item.id} | |
onPressItem={this.handleOnPressItem} | |
selected={!!selected.get(item.id)} | |
title={item.title} | |
/> | |
); | |
} | |
render() { | |
const { data } = this.props; | |
return ( | |
<FlatList | |
data={data} | |
extraData={this.state} | |
keyExtractor={item => item.id} | |
renderItem={this.renderItem} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment