Home > front end >  How to detect what item is on the screen in react-native FlatList?
How to detect what item is on the screen in react-native FlatList?

Time:01-05

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}
/>

CodePudding user response:

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);
          }
        }}

CodePudding user response:

You can wrap your renderItem with visibility sensor component

https://www.npmjs.com/package/@svanboxel/visibility-sensor-react-native

CodePudding user response:

You can use onViewableItemsChanged Flatlist property https://reactnative.dev/docs/flatlist#onviewableitemschanged

  •  Tags:  
  • Related