Skip to main content
Headshot of Damon Bauer Damon Bauer

Creating a better getItemLayout for SectionList in React Native

TLDR: Today, I published a new npm package called react-native-get-item-layout-section-list. This package is a helper for the getItemLayout prop in a SectionList in React Native.


Motivation

The getItemLayout prop in a SectionList is an optimization prop that improves performance of the list by helping it to quickly calculate the size and position of its items.

When you provide the getItemLayout prop, React Native can:

FlatList

In a FlatList, it's actually pretty trivial (especially with fixed item heights); you need to return an object with the length, offset, and index properties:

getItemLayout={(data, index) => ({
  length: ITEM_HEIGHT,
  offset: ITEM_HEIGHT * index,
  index,
})}

However, in a SectionList, it's a bit more complicated. The offset is calculated on a number of different things:

Additionally, the only real documentation for getItemLayout is on the FlatList page, and that doesn't help much when you're trying to figure out how to calculate the offset for a SectionList.

This is where the react-native-get-item-layout-section-list package comes in. It provides a helper function that allows you to pass all of the possible options that effect offset and performs the calculations for you.

Tags: