AppDividend
Latest Code Tutorials

React Native FlatList Example

10,634

Get real time updates directly on you device, subscribe now.

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

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

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 a data and then we will present that data in the FlatList component.  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 below.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 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 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'
  }
  
});

First, we have fetched the data from the server and then set the users state.

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

The renderItem() function renders the data and displays it on the screen. React component gives us the warning if we do not specify the key of the rendering object, 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

 

Related Posts
1 of 8

That is it for React Native FlatList Example. 

3 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

Leave A Reply

Your email address will not be published.

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