SectionList, Headers and Pull to Refresh

+15 Mana ✨

FlatList renders one flat array, but a task list grouped by day has two levels, the days and the tasks inside each one. SectionList takes that nested shape as it is and renders a header above each group.

Key terms

  • sections: the SectionList prop that holds the data, an array of section objects that each carry a data array of items plus any fields of your own, such as title.
  • renderSectionHeader: a function SectionList calls with {section} and renders at the top of each section.
  • Pull to refresh: swiping down on a list that is scrolled to the very top, which calls onRefresh so the app can load new data.
  • RefreshControl: the component that adds pull to refresh to a ScrollView or a list.

Each section carries its own data

sections is the SectionList counterpart of FlatList's data. Each section needs a data array with its items. Any other field is up to you, since a section is typed as data plus any other keys, so a title is not a built-in prop, only a name your header code reads. A section can also carry an optional key, which defaults to the section's array index. That default works as long as you don't reorder sections.

Grouping tasks by day

Each day becomes a section, and its tasks go in the section's data:

tsx
const sections = [
  {title: 'Today', data: [{id: 't1', text: 'Pay rent'}, {id: 't2', text: 'Call the dentist'}]},
  {title: 'Tomorrow', data: [{id: 't3', text: 'Water the plants'}]},
];

The header reads section.title from the argument it receives. In the TaskList example below the lesson, that is one line:

tsx
renderSectionHeader={({section}) => <Text style={styles.header}>{section.title}</Text>}

renderSectionFooter receives the same argument and is rendered at the bottom of each section. Either one renders nothing when you leave it out.

On iOS, section headers stick to the top of the screen until the next one pushes them off. stickySectionHeadersEnabled controls this and defaults to true on iOS and false on other platforms.

Rows and keys inside a section

renderItem is the default renderer for every item in every section, and a section can override it with a renderItem of its own. Its argument has four fields. item comes from that section's data, index is the item's position within its section, section is the full section object, and separators holds the same highlight, unhighlight and updateProps functions FlatList passes. An item's key joins the section's key with the item key from keyExtractor or the default extractor, so each task's id ends up in its key.

What renders around the rows

Five more props place content around the rows:

PropWhere it renders
ListHeaderComponentonce, at the very beginning of the list
ListFooterComponentonce, at the very end of the list
ListEmptyComponentwhen the list is empty
ItemSeparatorComponentbetween items, but not at the top or bottom
SectionSeparatorComponentat the top and bottom of each section

The first three accept either a component (EmptyTasks) or an element (<EmptyTasks />). A component passed as ListHeaderComponent is rendered with no props, so it never receives a section, and content that repeats for each section belongs in renderSectionHeader. The separator components do get the section among their props.

Separators follow section boundaries. ItemSeparatorComponent is skipped after the last item of a section, and a non-empty section with a SectionSeparatorComponent gets it twice, once before its first item and once after its last.

Whether ListEmptyComponent shows depends on the sections array as a whole. SectionList counts two cells per section, one for the header and one for the footer, on top of the items, and the empty component renders only when that count is 0. A section whose data is empty still counts. TaskList has one, {title: 'Next week', data: []}, so it filters the empty days out before passing them in:

tsx
sections={SECTIONS.filter(section => section.data.length > 0)}

With that filter, Nothing to do shows only when no day has a task.

Pull to refresh

Pass onRefresh and the list adds a standard RefreshControl for you. It also needs refreshing, a controlled boolean that should be true while new data is loading. Your onRefresh has to set it to true, otherwise the refresh indicator stops immediately, and set it back to false when the work is done. Leave refreshing out and the list fails with this error:

text
`refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `"undefined"`

The SectionList page lists false as the default of refreshing, but the list never falls back to it, so pass a boolean from the first render. TaskList keeps it in state with useState(false), and its onRefresh starts with setRefreshing(true).

To move the indicator down from the top, for example by 100 points, set progressViewOffset={100}. If you pass your own RefreshControl through refreshControl, the list uses yours and doesn't build one. A RefreshControl only works on a vertical ScrollView, so pull to refresh needs a list with horizontal left at false.

Code Examples

tsx
import {useCallback, useState} from 'react';
import {SectionList, StyleSheet, Text, View} from 'react-native';

type Task = {id: string; text: string};
type TaskSection = {title: string; data: Task[]};

const SECTIONS: TaskSection[] = [
  {title: 'Today', data: [{id: 't1', text: 'Pay rent'}, {id: 't2', text: 'Call the dentist'}]},
  {title: 'Tomorrow', data: [{id: 't3', text: 'Water the plants'}]},
  {title: 'Next week', data: []},
];

function Divider() {
  return <View style={styles.divider} />;
}

export default function TaskList() {
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    // a 2 second timer in place of a real request
    setTimeout(() => {
      setRefreshing(false);
    }, 2000);
  }, []);

  return (
    <View style={styles.screen}>
      <SectionList
        sections={SECTIONS.filter(section => section.data.length > 0)}
        renderItem={({item}) => <Text style={styles.task}>{item.text}</Text>}
        renderSectionHeader={({section}) => <Text style={styles.header}>{section.title}</Text>}
        ItemSeparatorComponent={Divider}
        ListHeaderComponent={<Text style={styles.title}>My tasks</Text>}
        ListEmptyComponent={<Text style={styles.empty}>Nothing to do</Text>}
        refreshing={refreshing}
        onRefresh={onRefresh}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {flex: 1},
  title: {fontSize: 24, fontWeight: 'bold', padding: 16},
  header: {fontSize: 14, fontWeight: 'bold', backgroundColor: '#f2f2f2', paddingHorizontal: 16, paddingVertical: 4},
  task: {fontSize: 18, padding: 16},
  divider: {height: 1, backgroundColor: '#dddddd'},
  empty: {padding: 16},
});
✓ Completed