Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native getItemLayout

Tags:

react-native

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
  };
}
like image 639
webjay Avatar asked Jul 07 '17 13:07

webjay


People also ask

What is getItemLayout in React Native?

To be straight the main purpose of getItemLayout is to load list faster or creating optimize FlatList in react native. What it does that it gives the boost of a FlatList containing hundreds of items. It will allow us to skipping measurement of dynamic content when we know the size of next item.

What is renderItem in React Native?

renderItem ​ renderItem({ item, index, separators }); Takes an item from data and renders it into the list. Provides additional metadata like index if you need it, as well as a more generic separators.

What is keyExtractor in React Native?

It extracts the unique key name and its value and tells the FlatList component to track the items based on that value. For the above array of data, modify the FlatList component and use the keyExtractor prop to extract the key: <FlatList data={DATA_WITH_ID} renderItem={renderList} keyExtractor={item => item.

How do I make my screen scrollable in React Native?

To set the ScrollView as Horizontal in React Native, use the ScrollView's prop as Horizontal = { true } . This makes this scroll view in a Horizontal format.


1 Answers

Its been long time, but for future readers thought to share some info.

There is a good article that explains the getItemLayout, please find it here

I also faced data[index] as undefined. The reason is that index is calculated considering section.data.length + 2 (1 for section header and 1 for section footer), you can find the code here (RN-52).

With SectionList we have to be very careful while processing index.

like image 135
Prasun Avatar answered Nov 10 '22 06:11

Prasun