Search code examples
reactjsreact-nativereact-native-flatlistflatlist

How to detect what item is on the screen in react-native FlatList?


I want to detect what item is showing on the screen in FlatList that render an aditional view in that item after 2 seconds of focus. (like comment filed in instagram)

In the Other word, I want to render an aditional view to PostItem after 2 seconds that it's showing on the screen. I try to add setTimeout in useEfect to make that component visible. But the PostItem in FlatList and all the list render concurrently and after 2 seconds all PostItems have this component.

Is there any solution for this? If the solution is to use onViewableItemsChanged​ prop in FlatList, how to implemet that with this prop?

here is my FlatList component:

const _renderItem: ListRenderItem<Post> = ({item}) => {
  return <PostItem {...item} />;
};

<FlatList
  data={data}
  keyExtractor={keyExtractor}
  renderItem={_renderItem}
  onEndReached={_onEndReached}
  onEndReachedThreshold={0.2}
  contentContainerStyle={styles.list}
/>

Solution

  • You can get the index of the element and find it in your data array using

      const onItemIndexChange = useCallback(setHourIndex, []);
    
      const ITEM_HEIGHT = height_of_one_item_rendered
    
          onMomentumScrollEnd={(ev) => {
              const newIndex = Math.round(ev.nativeEvent.contentOffset.y / ITEM_HEIGHT);
              if (onItemIndexChangeHour) {
                onItemIndexChange(newIndex + 1);
              }
            }}