Reputation: 2359
I using a react-native flatlist to render my data. I want to re-render data in flatlist when an item is pressed inside flatlist. How to achieve this?
const data = [
{
id: 1,
title: 'First Item',
isShow: 0
},
{
id: 2,
title: 'Second Item',
isShow: 0
}]
const renderItem = ({ item }) => {
return (
<TouchableOpacity onPress={() => onPress(item}>
<Text>{item.title}</Text>
</TouchableOpacity/>
);
};
const onPress = (item) => {
item.isShow = 1;
}
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
when item.isShow = 1
flatlist data should re-render.
Upvotes: 1
Views: 307
Reputation: 602
First your data used in the FlatList must be a state:
const [data, setData] = useState([]);
In your onPress
method you must do like this
const onPress = (item) => {
const newData = data.map(dataWithIsShow=> {
if(dataWithIsShow.id === item.id) {
dataWithIsShow.isShow = 1
return dataWithIsShow;
}
return dataWithIsShow
} )
setData(newData)
}
Got it? Please if you have more doubts you can ask :).
Upvotes: 1