1

I am trying to scroll to a particular index on flatlist. I am using the horizontal property of it. I am trying to scroll to a particular index using ref. But I am getting below error.

scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, otherwise there is no way to know the location of offscreen indices or handle failures.

Here is my code for Flatlist:

<FlatList
     ref={flatRef}
     showsHorizontalScrollIndicator={false}
     horizontal
     data={data}
     renderItem={renderCell}
   />

Here is code to scroll on a particular index:

flatRef.current.scrollToIndex({
  animated: false,
  index: index,
  viewPosition: 0.5,
});
Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56

2 Answers2

1

Follow this:

Flat List - ScrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

Add onScrollToIndexFailed prop as described in the above issue

0

Try this one adding onScrollToIndexFailed function

<FlatList
  ref={fListRef}
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 700));
    wait.then(() => {
      fListRef.current?.scrollToIndex({ index: info.index, animated: true/false });
    });
  }}
/>

You can checkout git repo as well :: https://github.com/facebook/react-native/issues/14198

Jay Mevada
  • 34
  • 2
  • This can end in a infinite wait time if the index item is far on the list and never rendered. It will just wait 700ms more for that item to be rendered and then will maybe go to it. If user don't scroll the list it will just wait for another 700ms. It should not be the accepted answer as it can lead to user scrolling manually and coming from nowhere the awaiting scrollToIndex is executed and move without user interaction => weird behaviour for UX. Generally speaking any solution based on magic waiting time is probably not a good one when dealing with UI events. – malko Nov 17 '22 at 15:29