Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native Flatlist getItemLayout with dynamic item height

Tags:

react-native

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; }}
/>
like image 818
Tzvetlin Velev Avatar asked Apr 13 '18 19:04

Tzvetlin Velev


People also ask

How do you adjust the height of a FlatList?

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.

How do I use onScrollToIndexFailed?

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.


2 Answers

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.

like image 139
Dror Biran Avatar answered Oct 16 '22 15:10

Dror Biran


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.

like image 2
Tzvetlin Velev Avatar answered Oct 16 '22 14:10

Tzvetlin Velev