SectionList and Pull to Refresh
As Sprout grows, users want plants grouped by room: Kitchen, Bedroom, Balcony. They also expect the universal phone gesture: pull the list down, see a spinner, get fresh data. Two tools handle this: SectionList and pull-to-refresh.
The rule
Sections are titles with data arrays; refreshing needs a flag and a handler.
SectionList is a virtualized list with group headers. Its data is an array of sections, each with a title and its own data array:
const rooms = [
{ title: 'Kitchen', data: [basil, mint] },
{ title: 'Bedroom', data: [fern] },
{ title: 'Balcony', data: [cactus, tomato] },
];
<SectionList
sections={rooms}
keyExtractor={(plant) => plant.id}
renderItem={({ item }) => <PlantCard plant={item} />}
renderSectionHeader={({ section }) => (
<Text style={styles.room}>{section.title}</Text>
)}
stickySectionHeadersEnabled
/>- The key must be named
datainside each section. Other fields, liketitle, are yours to choose. renderSectionHeaderreceives{ section }, the whole section object.- Sticky headers keep the current room's title pinned at the top while you scroll. They are on by default on iOS.
Both list components only re-render when their props change. If you push a new plant into the existing array, the list may not notice. Build a new array instead, such as [...plants, newPlant], and regroup the sections from it.
Pull to refresh. FlatList and SectionList have it built in. Give them two props:
<FlatList
data={plants}
renderItem={renderPlant}
refreshing={isRefreshing}
onRefresh={reloadPlants}
/>onRefresh runs when the user pulls down. Your handler sets isRefreshing to true, loads data, then sets it back to false. The spinner stays until the flag goes false, so forgetting that last step leaves it spinning forever.
For a plain ScrollView, use the RefreshControl component itself:
<ScrollView
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={reloadPlants} />
}
>The shortcut
When data has groups, reshape it before you render it: turn a flat array into [{ title, data }], then the SectionList props almost write themselves.
Start flat
plantsis one array; each plant has aroomfield.
Drills
Answer fast — trust the rule.
In a SectionList, what must each section's list of items be called?
What does renderSectionHeader receive?
After a pull to refresh, the spinner never stops. What is the likely bug?
How do you add pull to refresh to a plain ScrollView?
Remember
- Sections are
{ title, data }; refreshing needs arefreshingflag andonRefresh. - Reshape grouped data first, then render.
- Trap: forgetting to set
refreshingback tofalse.
