Explanation and example of React Native FlatList

React native FlatList :

FlatList is used to show a list of items in react-native. It is actually a list view with the most important list features like header support, footer support, separator support, pull to refresh support, multiple columns, scrollable to an index programmatically, scroll loading, etc.

In this tutorial, we will learn how to use FlatList in react native with an example.

Example of FlatList :

In this example, we will load the data from an array of objects to a FlatList. Let’s move to the example :

import React from 'react';
import {StyleSheet, View, Text, FlatList, SafeAreaView} from 'react-native';

const days = [
  {id: '1', name: 'One'},
  {id: '2', name: 'Two'},
  {id: '3', name: 'Three'},
  {id: '4', name: 'Four'},
  {id: '5', name: 'Five'},
  {id: '6', name: 'Six'},
  {id: '7', name: 'Seven'},
  {id: '8', name: 'Eight'},
  {id: '9', name: 'Nine'},
  {id: '10', name: 'Ten'},
  {id: '11', name: 'Eleven'},
  {id: '12', name: 'Twelve'},
  {id: '13', name: 'Thirteen'},
  {id: '14', name: 'Fourteen'},
];

const ListItem = ({index}) => {
  return (
    <View style={styles.listItem}>
      <Text style={styles.listText}>{days[index].name}</Text>
    </View>
  );
};

const App = () => {
  return (
    <SafeAreaView style={styles.parentView}>
      <FlatList
        style={styles.flatList}
        data={days}
        renderItem={({index}) => <ListItem key={index} index={index} />}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  parentView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 22,
  },
  flatList: {
    width: '100%',
  },
  listText: {
    color: 'white',
  },
  listItem: {
    flex: 1,
    marginRight: 20,
    marginLeft: 20,
    marginTop: 10,
    backgroundColor: '#776677',
    padding: 10,
    borderRadius: 5,
  },
});

export default App;

Explanation :

  1. Here, days is an array of objects we are loading to a FlatList.

  2. We are using two props here. data that takes an array of items. renderItem is a function that is called for each item in data to render the list item.

  3. ListItem component loads one item of a list.

Output :

If you run this example, it will give the below output :

React Native flatlist