Categories
React Native

React Native — Section List and Back Button Handling

Spread the love

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

SectionList

We can add the SectionList component to display a section list view.

It’s cross-platform and works with horizontal mode.

Also, it has header, footer, and separator support.

We can pull it to refresh the data.

We can load data as we scroll with it.

And it also has multiple columns support.

For example, we can write:

import React from 'react';
import { SafeAreaView, StyleSheet, Text, View, SectionList } 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>
);
export default function App() {
  return (
    <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,
    marginTop: 0
  },
  item: {
    backgroundColor: 'pink',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

We add the SafeAreaView and the SectionList to display a list with section headings and each section having their own content.

The sections prop has the data.

keyExtractor is a function that returns the unique index for the item.

renderItem is a function that renders the item.

The renderSectionHeader prop renders the header with a function.

BackHandler

We can use the BackHandler API to handle back button presses.

For instance, we can write:

import React, { useEffect } from 'react';
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";

export default function App() {
  useEffect(() => {
    const backAction = () => {
      Alert.alert("Are you sure?", "Are you sure you want to go back?", [
        {
          text: "Cancel",
          onPress: () => null,
          style: "cancel"
        },
        { text: "YES", onPress: () => BackHandler.exitApp() }
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );

    return () => backHandler.remove();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Click Back button!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

We attach an event handler for the hardwareBackPress event with BackHandler.addEventListener .

In the backAction event handler function, we show an alert with the Alert.alert method.

It takes the title and the content for the alert as the argument.

The 3rd argument is an array with the objects having the content of the cancel button.

The text property is the text for the button.

onPress is a function that runs when we press the button.

style has the style for the button.

When the component unmounts, we call backHandler.remove() to remove the hardwareBackPress listener.

Conclusion

We can add the SectionList component to add a list with section headings and list items for each section.

Also, we can add a handler for the back button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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