setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100);
If i use scrolltoindex in flat list return to me this error;
scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed
I tried to use getItemLayout but my flatlist items have different height, how can i fix this?
getItemLayout={(data, index) => (
{length: 40, offset: 40 * index, index}
)}
onScrollToIndexFailed Used to handle failures when scrolling to an index that has not been measured yet. Recommended action is to either compute your own offset and scrollTo it, or scroll as far as possible and then try again after more items have been rendered.
You can use FlatList onViewableItemsChanged prop to get what you want. viewabilityConfig can help you to make whatever you want with viewability settings. In code example 50 means that item is considered visible if it is visible for more than 50 percents.
I had a similar error with a horizontal list showing images where the selected image should be shown in a carousel when pressed.
I solved it by setting the selected index on the FlatList
by using initialScrollIndex
. I also used onScrollToIndexFailed
to scroll to the correct image for the times when initialScrollIndex
failed to show the correct image.
This is done by setting a timeout for 500ms and then scroll to the selected image.
Complete example (with only the props regarding this error):
const flatList = useRef<FlatList>(null);
...
<FlatList
ref={flatList}
initialScrollIndex={props.activeIndex}
onScrollToIndexFailed={info => {
const wait = new Promise(resolve => setTimeout(resolve, 500));
wait.then(() => {
flatList.current?.scrollToIndex({ index: info.index, animated: true });
});
}}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With