Creating a list of items in my project using flatlist. My items rendering fine in the list.
There is 1 favorite icon there to select the product as favorite. From my data i am changing the icon on the base either this product is favorite or not.
what i want is to bind each product to mark as favorite and change the color. in short needs to toggle favorite and not favorite icon.
My code
Data i am rendering
entries: [
{ id: 1, is_fav: false, title: 'hello', ImagePath: 'https://cdn.pixabay.com/photo/2012/03/01/00/55/flowers-19830_960_720.jpg' },
{ id: 2, is_fav: true, title: 'world', ImagePath: 'https://cdn.pixabay.com/photo/2017/07/01/19/48/background-2462434_960_720.jpg' },
{ id: 3, is_fav: false, title: 'you', ImagePath: 'https://cdn.pixabay.com/photo/2016/12/16/15/25/christmas-1911637_960_720.jpg' },
{ id: 4, is_fav: true, title: 'you', ImagePath: 'https://cdn.pixabay.com/photo/2015/07/10/17/27/sparkler-839831_960_720.jpg' },
{ id: 5, is_fav: false, title: 'hello', ImagePath: 'https://cdn.pixabay.com/photo/2012/03/01/00/55/flowers-19830_960_720.jpg' }]
Flatlist
<FlatList
data={this.state.entries}
numColumns={this.state.columns}
key={this.state.key}
renderItem={this.Render_flatlist_Data}
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={this.Render_FlatList_Sticky_header}
stickyHeaderIndices={[0]}
/>
Render_flatlist_Data = ({ item: rowData }) => {
.....
<TouchableOpacity onPress={() => this.TickFav()}>
<Text>
<Icon name={(rowData.is_fav === true ? 'heart' : 'ios-heart-empty')}
size={25} color="#ddd" /> </Text>
</TouchableOpacity>
.....
}
How i can make the product fav when click on the product favorite icon.
Thanks in advance.
First of all we need to have a variable to watch [extraData] that the state data has been changed. (i.e) some product has been marked or un-marked as favourite.
This helps the flatlist to notify that a value has been changed, so that we have to re-render.
In Your case, adding extraData field in Flatlist should do fine
<FlatList
data={this.state.entries}
extraData={this.state}
numColumns={this.state.columns}
key={this.state.key}
renderItem={this.Render_flatlist_Data}
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={this.Render_FlatList_Sticky_header}
stickyHeaderIndices={[0]}
/>
TickFav = rowData => {
rowData.is_fav = !rowData.is_fav
this.setState({});
}
You can even get the actual rowData from the state and change it directly, which is not needed.
TickFav = (index) => {
const {entries} = this.state;
entries[index].is_fav = !entries[index].is_fav;
this.setState({entries});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With