Search code examples
reactjsreact-nativereact-native-flatlistscrolltoindex

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


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

Solution

  • 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