React Native getItemLayout

Viewed 9068

I am implementing a SectionList showing a list of weeks which needs to scroll to the current week, thus I am using initialScrollIndex.

The problem I face is that I don't really understand what the index given to my _getItemLayout is? Sometimes data[index] === undefined, which doesn't make sense to me.

I need to know which section it is (data[?]) as each section contains another SectionList for the events that week, thus height isn't a constant.

_getItemLayout = (data, index) => {
  const rows = (data[index] === undefined) ? 1 : data[index].data.reduce((sum, value) => value.data.length + sum, 0);
  const height = (rows * 94);
  return {
    length: height,
    offset: height * index,
    index
  };
}
3 Answers

Similar to uxxi we ended up writing up our own implementation based off of react-native-get-item-layout but there is an important distinction to make.

Wiring either method to the SectionList getItemLayout parameter re-executes the same iterations over the data for every item being rendered. The overhead added by this is substantial and after correcting for the same there is a significant performance improvement.

Essentially the key is to calculate your offset data whenever the data provided to the component changes it's shape and then call against that calculated data to obtain the offset for getItemLayout. This will result in a single iteration per data change vs endless iterations per interaction with the list.

For some reason the react-native-get-item-layout package keeps crashing with "height: <<NaN>>" so I had to write my own RN SectionList getItemLayout . It uses the same interface as the former. Like the package it's also an O(n).

Related