How to use SectionList Component in React Native?

Apr 29, 2022 . Admin

Hello Dev,

In this short tutorial we will cover a react native SectionList example. it's a simple example of how to use SectionList in react native. step by step explain SectionList example in react native. This tutorial will give you a simple example of how to create a SectionList in react native. So, let's follow a few steps to create an example of how to use SectionList component using react native.

Here I will give you many example of how to make SectionList in react native.

First of all you can import StatusBar, StyleSheet, Text, View, and SectionList from react-native. Next, a create object name as 'COUNTRIES' and key/value pair title and data is put into the object. you can create multiple values in an array. Next, a create function name as CustomSectionList.After then you can create the VIEW component and SectionList component and put them into the CustomSectionList function.

  1. Sections prop required for rendering data into sectionlist
  2. renderItem prop will tell how to render the items from the list.
  3. The renderSectionHeader prop displays the header section of the list view.
  4. keyExtractor is Used to extract a unique key for a given item at the specified index.

Step 1 : Create project

Let's run the following command.

expo init SectionListApp 
Step 2 : App.js

In this step, You will open App.js file and put the code.

import React from 'react'
import { StatusBar, StyleSheet, Text, View, SectionList } from 'react-native'

const COUNTRIES = [
    {
        title: 'A',
        data: ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Australia']
    },
    {
        title: 'B',
        data: ['Brazil', 'Bhutan', 'Brunei', 'Bulgaria', 'Bangladesh']
    },
    {
        title: 'C', 
        data: ['China', 'Canada', 'Colombia', 'Costa Rica', 'Cuba',]
    },
];

const CustomSectionList = () => {
    return (
        <View style={styles.container}>
            <SectionList
                sections={COUNTRIES}
                renderItem={({ item }) => <Text style={[styles.item, styles.title]}>{item}</Text>}
                renderSectionHeader={({ section }) => <Text style={styles.header}>{section.title}</Text>}
                keyExtractor={(index) => index}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: StatusBar.currentHeight,
    },
    item: {
        backgroundColor: "#f9c2ff",
        padding: 20,
        marginVertical: 2,
    },
    header: {
        fontSize: 32,
        backgroundColor: "red",
        color: 'white',
        textAlign: 'center',
    },
    title: {
        fontSize: 24
    },
});

export default CustomSectionList;
Step 3 : Run project

In the last step run your project using bellow command.

expo start 
Output :

It will help you...

#React Native