React-Native: Getting an error when scrollToIndex using FlatList ref

4.5k Views Asked by At

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

There are 2 best solutions below

1
Jay Mevada On BEST ANSWER

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

0
Muhammad Umer Qadri On

Follow this:

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

Add onScrollToIndexFailed prop as described in the above issue