Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check visibility of item in FlatList at different visibility percentages?

I am trying to perform an action on a given item inside of React Native FlatList when it becomes visible in 2 different scenarios:

  1. When the item is 10% visible (perform fade/scale animation)
  2. When the items is 100% visible (start playing video/audio when on screen)

From the RN documentation, it states that is it not possible to change the viewabilityConfig on demand.

How can this be done? Thanks.

like image 300
Carlos Pinto Avatar asked May 18 '18 15:05

Carlos Pinto


People also ask

How do I get the current visible index in RN FlatList?

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.

What is the use of keyExtractor in FlatList?

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.

How do I scroll to specific index in FlatList React Native?

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.


1 Answers

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
  }
];
like image 166
Carlos Pinto Avatar answered Nov 15 '22 14:11

Carlos Pinto