React Native
SectionList
Learn grouped lists with SectionList.
SectionList
SectionList shows lists grouped into sections. While FlatList takes a flat array, SectionList takes an array of section objects. Each section has a title and a data field. It is ideal for splitting an address by city or a menu by category.
Example: sections=[{ title: 'Fruits', data: ['Apple', 'Pear'] }, { title: 'Vegetables', data: ['Tomato', 'Pepper'] }]. renderItem draws each item; renderSectionHeader draws each section's header. The list is visually split into sections.
Exercise Write a grouped list
Complete the empty component. The sections array is defined: two sections, each with title and data fields. Return <SectionList sections={sections} renderItem={({ item }) => <Text>{item}</Text>} renderSectionHeader={({ section }) => <Text style={{ fontWeight: 'bold' }}>{section.title}</Text>} keyExtractor={(item, index) => index.toString()} />.
Show example solution
import React from 'react';
import { SectionList, Text } from 'react-native';
export default function GroupedList() {
const sections = [
{ title: 'Fruits', data: ['Apple', 'Pear'] },
{ title: 'Vegetables', data: ['Tomato', 'Pepper'] }
];
return (
<SectionList
sections={sections}
renderItem={({ item }) => <Text>{item}</Text>}
renderSectionHeader={({ section }) => <Text style={{ fontWeight: 'bold' }}>{section.title}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
);
}
renderSectionHeader
To show a header above each section, use renderSectionHeader. This function takes an object whose section property is the section itself. section.title is the header text. The header can be set apart from other items with a bold font or a different background.
Example: renderSectionHeader={({ section }) => <Text style={{ fontWeight: 'bold' }}>{section.title}</Text>}. This pattern shows a bold header above each section. Headers can be sticky on mobile; this behavior is enabled with the stickySectionHeadersEnabled prop.
Test yourself
-
What data structure does SectionList take?
<SectionList
???={[
{ title: 'A', data: [...] }
]}
/>
Show answer
sections — The sections prop takes an array of section objects.
-
Write the renderSectionHeader parameter
renderSectionHeader={({____}) => <Text>{section.title}</Text>}
Show answer
renderSectionHeader={({section}) => <Text>{section.title}</Text>}
-
Match each SectionList prop to its job
- sections
- Section array
- renderItem
- Draws each item
- renderSectionHeader
- Draws section header
- section.title
- Header text
Next lesson: List header and footer