AppDividend
Latest Code Tutorials

React Native FlatList | How To Use React Native FlatList

6

React Native FlatList Example | How To Use React Native FlatList is the topic, we will discuss.  There have been quite a few ways to create a scrolling list in React Native, and most notably, they have been the ScrollView and the FlatList. FlatList offers the following handy features.

Overview of React Native FlatList Example

  • Step 1: Install React Native on mac.
  • Step 2: Create sample data.
  • Step 3: Create a backend server.
  • Step 4: Create a service that fetchs the data from the backend server.
  • Step 5: Display the user data to the screen.

FlatList Features

  • Fully cross-platform.
  • Optional horizontal mode.
  • Configurable viewability callbacks.
  • Header support.
  • Footer support.
  • Separator support.
  • Pull to Refresh.
  • Scroll loading.
  • ScrollToIndex support.

React Native FlatList Example

We will understand the FlatList Component using the Example. We will create a server and then send a network request to the server, and in response, we get data, and then we will present that data in the FlatList component. 

What is React Native FlatList

What is the FlatList component? It’s an easy way to make an efficient scrolling list of data. Not only is it practical, but it’s got an incredibly simple API to work with.

If you’ve used or are familiar with the ListView component, it’s very similar, just better in (almost) every way. 😀 No longer do you have to format the data — you can pass it an array of data and get to rendering right away.

There are two primary props you need to know about in the FlatList, and that’s data and renderItem. The first is an array of data used to create the list, typically a variety of objects, and the second is the function that will take an individual element of the data array and render a component for it.

As usual, we will start this tutorial by installing the React Native On Mac using the react-native-cli.

Step 1: Install React Native On Mac

Go to the terminal and hit the following command.

react-native init FlatListApp

It will install the dependencies and gives some boilerplate. Go into the project directory.

cd FlatListApp

Now, start the package manager and the simulator by the following command. I am using iPhone X as a Simulator.

react-native run-ios --simulator="iPhone X"

The first time, it will take 2-3 minutes to compile, and then you can see on your iPhone X screen like the below image.

React Native FlatList ExampleStep 2: Create the sample data and server.

We need the fake data to work with the React Native FlatList Example; that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using the Yarn package manager.

yarn add json-server

Okay, now we need to create one folder called data inside the root folder, and in that folder, create one file called db.json. For the testing purpose, let us add the following data in the db.json file.

{
    "users": 
        [
            {
                "name": "Proxima Midnight",
                "email": "proxima@appdividend.com"
            },
            {
                "name": "Ebony Maw",
                "email": "ebony@appdividend.com"
            },
            {
                "name": "Black Dwarf",
                "email": "dwarf@appdividend.com"
            },
            {
                "name": "Mad Titan",
                "email": "thanos@appdividend.com"
            },
            {
                "name": "Supergiant",
                "email": "supergiant@appdividend.com"
            },
            {
                "name": "Loki",
                "email": "loki@appdividend.com"
            },
            {
                "name": "corvus",
                "email": "corvus@appdividend.com"
            },
            {
                "name": "Proxima Midnight",
                "email": "proxima1@appdividend.com"
            },
            {
                "name": "Ebony Maw",
                "email": "ebony1@appdividend.com"
            },
            {
                "name": "Black Dwarf",
                "email": "dwarf1@appdividend.com"
            },
            {
                "name": "Mad Titan",
                "email": "thanos1@appdividend.com"
            },
            {
                "name": "Supergiant",
                "email": "supergiant1@appdividend.com"
            },
            {
                "name": "Loki",
                "email": "loki1@appdividend.com"
            },
            {
                "name": "corvus",
                "email": "corvus1@appdividend.com"
            }
        ]
}

Okay, so now this is the file, the json-server will server when we hit the network request. So type the following command to start the json-server.

json-server tutorial

Switch to the browser and go to this URL: http://localhost:5200/users

 You can see that we are receiving the JSON response from that db.json file.

Step 3: Create a service that fetches the data from the server.

In the root folder, create one folder called service, and in that folder, create one file called FetchData.js.

// FetchData.js

const URI = 'http://localhost:5200';

export default {
    async fetchUsers() {
        try {
                let response = await fetch(URI + '/users');
                let responseJsonData = await response.json();
                return responseJsonData;
            }
        catch(e) {
            console.log(e)
        }
    }
}

Fetch is the network library provided by React Native. It is a promise-based library, so we need to wait to resolve it. Here we have used async/await.

Step 4: Modify the App.js file to display the users’ data.

We will display the users’ data in FlatList.

// App.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList
} from 'react-native';
import ajax from './service/FetchData';

export default class App extends Component {

  state = {
    users: []
  }

  async componentDidMount() {
    const users = await ajax.fetchUsers();
    this.setState({users});
  }


  render() {
    return (
      <View style={styles.container} >
        <Text style={styles.h2text}>
          Black Order
        </Text>
          <FlatList
          data={this.state.users}
          showsVerticalScrollIndicator={false}
          renderItem={({item}) =>
          <View style={styles.flatview}>
            <Text style={styles.name}>{item.name}</Text>
            <Text style={styles.email}>{item.email}</Text>
          </View>
          }
          keyExtractor={item => item.email}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  h2text: {
    marginTop: 10,
    fontFamily: 'Helvetica',
    fontSize: 36,
    fontWeight: 'bold',
  },
  flatview: {
    justifyContent: 'center',
    paddingTop: 30,
    borderRadius: 2,
  },
  name: {
    fontFamily: 'Verdana',
    fontSize: 18
  },
  email: {
    color: 'red'
  }
  
});

With that completed, you can go ahead and start rendering the data. To do so, the first thing you want to do is import { StyleSheet, Text, View, FlatList } from “react-native,“; so you have the necessary components to render the data.

The remainder of the work will take place in the render method. First, we have fetched the data from the server and then set the users state.

FlatList consumes that users’ data via this.state.users.

Then you want to render the content with the renderItem prop. The function is passed a single argument, which is an object.

The data you’re interested in is on the item key so you can use destructuring to access that from within the function. Then return a component utilizing that data.

If you find any warning that the elements of the list are missing keys, these unique keys are what allow the VirtualizedList (which is what FlatList is built on) to track items and aids in the efficiency of the list. I won’t dive into it, but know that it’s essential.

To alleviate this issue, you want to choose a piece of data that is unique to each item. In this case, you can use the user’s email address because that will be unique to each item. You can then use the keyExtractor prop to specify which piece of data should be used as the key.

 So, we have defined the unique key from our data.

I have hidden the verticle scrollbar using property showsVerticalScrollIndicator={false}. Our final output looks like this.FlatList in React Native

That is it for React Native FlatList.

Finally, React Native FlatList Example | How To Use React Native FlatList Tutorial is over.

Recommended Posts

React Native Swipe Components Example

React Native Drawer Navigator Example

React Native Tab View Example

Native Navigation using React Native Navigation

React Native Redux Example Tutorial

React Native Modal Example

React Native Create Delete Functionality

React Native Animation Tutorial

React Native Firebase Example

React Native Flexbox Tutorial

6 Comments
  1. Marcondes Amaral de Oliveira says

    Hi, man. The list from db.json just dont appears. Can you help me? The code is ‘copy & paste’ from here. Thanks

  2. anil rathod says

    it is possible to fetch json data without listview or flatlist?
    like in simple view or swipeview?

  3. AiMechanic says

    To make it work in Android Emulator, the address of the development machine is 10.0.2.2 not localhost. Replace “const URI = ‘http://localhost:5200’;” with “const URI = ‘http://10.0.2.2:5200’;” in FetchData.js
    Read more on StackOverflow: https://stackoverflow.com/questions/9808560/why-do-we-use-10-0-2-2-to-connect-to-local-web-server-instead-of-using-computer

    1. ndhung says

      thanks you very much :D. Your comment makes my life easier.

  4. Rohit Patil says

    How to make scrollToTop in Flatlist?

  5. fb3hrf says

    Hi, man. The list from db.json just dont appears. Can you help me? The code is ‘copy & paste’ from here.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.