I am trying to perform an action on a given item inside of React Native FlatList
when it becomes visible in 2 different scenarios:
From the RN documentation, it states that is it not possible to change the viewabilityConfig
on demand.
How can this be done? Thanks.
To get the index of the currently visible item in a React Native flat list, we can set the onViewableItemsChange prop to a function that gets the current visible items. to define the onViewableItemsChanged function that gets the viewableItems property. viewableItems has the items that are current visible on the screen.
keyExtractor Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key , then item.id , and then falls back to using the index, like React does.
We would use Ref. scrollToIndex() inbuilt function of FlatList here. To use this function first we have to make a reference of our FlatList component then we can call this function.
I just noticed that FlatList
takes a prop called viewabilityConfigCallbackPairs
whose format is not fully documented at https://facebook.github.io/react-native/docs/virtualizedlist.html#viewabilityconfigcallbackpairs
Basically what this does is that it will take an array of objects with key/value pairs for viewabilityConfig
and onViewableItemsChanged
. This will allow you to define any handlers for each different viewability configurations.
For example:
<FlatList
data={items}
renderItem={this.renderItem}
keyExtractor={(item) => item.id }
refreshing={false}
onRefresh={this.onRefresh}
viewabilityConfigCallbackPairs={this.viewabilityConfigCallbackPairs}
/>
Where this.viewabilityConfigCallbackPairs
would equal:
this.viewabilityConfigCallbackPairs = [{
viewabilityConfig: {
minimumViewTime: 500,
itemVisiblePercentThreshold: 100
},
onViewableItemsChanged: this.handleItemsInViewPort
},
{
viewabilityConfig: {
minimumViewTime: 150,
itemVisiblePercentThreshold: 10
},
onViewableItemsChanged: this.handleItemsPartiallyVisible
}
];
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