How to Use the SectionList Component — React Native Basics
Since the release of v0.43 of React Native, we have two new components for presenting lists of data, the FlatList
and the SectionList
. Today we will be looking at the SectionList
component.
Introducing the SectionList Component
The SectionList
component allows us to create a list of content that is broken up into scrollable sections. SectionLists are similar to Flatlists, but they extend the FlatList functionality even further.
Using the SectionList Component
In this example, we will be creating a simple SectionList of hardcoded data. Each item in the data props is rendered as a Text
component.
First, let’s make sure we have imported SectionList
along with other necessary imports for this example.
Next let’s implement a render
method in our class and return a SectionListComponent
wrapped by root View
component.
But there are some key props that we would have to pass. First, we should be able to get the data to the SectionList, and we would achieve this through the sections
prop. The sections
prop holds an array of data that would be representing each section, and each item in the array is going to be an object.
Now let’s pass some data to it.
As seen above, the title
is what we would be using for our section titles which would be visible as the header of our individual sections. The data
represents an array used to create the list, typically an array of objects.
The next required prop that is expected is the renderItem
, which would be responsible for rendering each one of the individual items in our data array. The renderItem
prop is a function that takes an item
from the data array and returns a React element.
item
, as shown in the code above, represents each item in the data array.
Next, we wan add the renderSectionHeader
prop. The renderSectionHeader
displays the header section of the list view.
We should not forget to add the keyExtractor
function which allows for tracking the items. Or as stated by the React Native docs:
Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks
item.key
, then falls back to using the index, like React does.
Here is what we have
Lastly, to get yours looking like the screenshot above, you could add the style below.
Complete Source Code
The complete source code that helped us demonstrate this concept is given below: