0

How do I get the current index of item at which the flatlist has stopped scrolling at and has snapped to?

const Scrollref=useRef();

<FlatList
    data={Data}
    ref={Scrollref}
    renderItem={...}
    keyExtractor={...}
    getItemLayout={...}
    initialScrollIndex={initialScrollIndex}
    initialNumToRender={3}
    snapToOffsets={Data.map((x, i) => (i*ITEM_HEIGHT))}
/>

I used this solution and although it does give the key index from viewableItems, it returns so on everytime the view is changed which seems very inefficient

is there anyway to get the key after the scrolling has stopped? maybe using onMomentumScrollEnd?

  • you can use "onViewableItemsChanged" . check this [answer](https://stackoverflow.com/a/45869559/2198380) – pfndesign Oct 25 '21 at 20:48
  • @pfndesign sorry I'm new to react native so I don't really understand it, could u elaborate or answer using the answer you've provided as a reference? –  Oct 25 '21 at 20:53
  • sure . first all itemVisiblePercentThreshold inside of the viewabilityConfig props. it takes a value between 0-100 percent witch means the percentage of item that has to be inside of the viewport to be considered visible . onViewableItemsChanged props accept a function that triggered each time viewable Items changed like snapping or scrolling . viewableItems return an [ViewToken](https://reactnative.dev/docs/viewtoken) . you can access the current active index like this viewableItems[0].index or viewableItems[0].item for item data . viewableItems can return more than one item – pfndesign Oct 25 '21 at 21:10
  • @pfndesign I understand now but the problem is that it returns the viewableItem after changing the view is there no way to get it after someone has stopped scrolling? (I've edited the question for further details) –  Oct 25 '21 at 21:37
  • you can save viewableItems in a state then get the last one in the onMomentumScrollEnd event or onScrollEndDrag or you can increase the value of the itemVisiblePercentThreshold so onViewableItemsChanged called less often or you can enable paging with pagingEnabled prop so it will be called when scroll stops . – pfndesign Oct 25 '21 at 21:54

0 Answers0