react native-tutorial

React Native SectionList

The SectionList Component is an inbuilt React Native list view component that renders sectioned lists. As the name suggests, it is used to display lists of data in different sections. It is a pure component, supporting most of the features like pull-to-refresh, scroll loading, separators, headers, and footers, etc. SectionLists are primarily used for displaying lists in sections. In the case that section support is not required, a FlatList or ScrollView component should be used.

Syntax:

<SectionList
      sections={}
      renderItem={}
/>

Useful SectionList properties

Let’s focus on a few SectionList tools you should be aware of in more detail: onEnReached and ItemSeparatorComponent.

  • ItemSeparatorComponent is helpful when you want to show any view as a separator of every item in the SectionList
  • onEndReached is called when you scroll to the bottom of the list. It can be helpful if you want to load some data when you are at the bottom of the list

Step 1: Open your terminal and install expo-cli by the following command.

npm install -g expo-cli

Step 2: Now create a project by the following command.

expo init sectionlist-demo

Step 3: Now go into your project folder i.e. sectionlist-demo

cd sectionlist-demo

Code

App.js

import React from "react";
import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar } from "react-native";

const DATA = [
  {
    title: "Main dishes",
    data: ["Pizza", "Burger", "Risotto"]
  },
  {
    title: "Sides",
    data: ["French Fries", "Onion Rings", "Fried Shrimps"]
  },
  {
    title: "Drinks",
    data: ["Water", "Coke", "Beer"]
  },
  {
    title: "Desserts",
    data: ["Cheese Cake", "Ice Cream"]
  }
];

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

const App = () => (
  <SafeAreaView style={styles.container}>
    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  </SafeAreaView>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: StatusBar.currentHeight,
    marginHorizontal: 16
  },
  item: {
    backgroundColor: "#f9c2ff",
    padding: 20,
    marginVertical: 8
  },
  header: {
    fontSize: 32,
    backgroundColor: "#fff"
  },
  title: {
    fontSize: 24
  }
});

export default App;

Output:

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *