I am trying to implement a scrollToIndex function on a flatlist so that it scrolls to a specific item when it renders. The issue I am running into is that the items the flatlist renders have a minHeight
. The issue with that is, the flatlist needs to implement a function to calculate the offset for every element. I cant think of a way to pre-render
the flatlist and get the height of every item in it. As you can see I am simply adding a static number for the offset and that is not what I need.
<FlatList
data={data}
renderItem={this.renderItem}
getItemLayout={(dat, index) => {
let offset = 0;
for (let i = 0; i < index; i++) {
if (data[i].headerText) {
offset += 33;
} else {
offset += 80;
}
}
return { length: 0, offset, index }
}
}
ref={(ref) => { this.flatListRef = ref; }}
/>
To change the height of a FlatList in React Native, we can set the height of the View that we wrap around the FlatList . to set the height of the View to 300px to make the height of the FlatList 300px.
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.
I followed @Tzvetlin Velev answer and here is an example: https://snack.expo.io/@drorbiran/scrolltoindex-with-random-item-heights-
I'm calculating each item height in onLayout and in getItemLayout I'm summing up the heights of all the elements above it.
The View
that wraps each component rendered in the Flatlist can invoke a callback called onLayout which provides information about the component. You can manage a array on the context of a parent component that doesn't unmount with unique ids of every component(easy for me with relayjs' unique relay ids'. onLayout you can add its dimensions and reference id so that when you calculate the offset, you have those dimensions. When a component in the list unmounts you can remove it from that array.
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