React Native Infinite List FlatList Pagination to Load More JSON Data dynamically on Button Click Tutorial

The Infinite List is a type of ListView – FlatList used to show only fixed number of data on application startup time and user can himself Load More Data if required on Button Click event. The Infinite List can show hundreds of records without lagging and application hanging process because of its quick way process method. It only loads fixed number of data and itself pass a paging parameter with HTTP URL so by using the application developers can tell the server to load new data and the data present on PHP MySQL server. So in this tutorial we would going to implement Infinite List FlatList Pagination to Load More JSON Data dynamically on Button Click Example Tutorial.

Live Screenshot of App:

Contents in this project Infinite List FlatList Pagination to Load More JSON Data dynamically on Button Click Tutorial in React Native:

1. Create new database on your MySQL PhpMyAdmin panel.

2. Create a new table named as Chart with 2 columns id and value. The id is auto increment and as declared as primary key and value is varchar type. Now we would store one to hundred table inside the MySQL database table. After inserting records in table we have 100 records inside the table, Below is the screenshot of table.

3. Creating PHP script to convert MySQL data into JSON :

We are using PHP to convert MySQL database data into JSON form, We would use the Get method of PHP and split all the data into multiple segments(pages), so we have to pass the page number along with the URL and it will show record according to that URL. There is a fixed condition in PHP Code though it will only show 10 Records at a single time.

DBConfig.php file : This file contain all the useful information about your server.

counting_table.php : This file would convert the MySQL data into JSON and show only 10 records at a single time. User need to pass the page number along with URL. The URL of this page should look like this:

We need to pass the Page number with URL so it will divide the records and show filtered records according to give page number.

Code for DBConfig.php file : 

Code for counting_table.php file:

Screenshot of JSON :

4. Start a new react native project, If you don’t know how to then read my this tutorial.

5. Import StyleSheet, View, Text, Platform, FlatList, TouchableOpacity and ActivityIndicator component in your project.

5. Create constructor() in your class, Now we would make 3 states named as isLoading, JSON_from_server and fetching_Status inside constructor(). We would also make a this variable named as this.page.

isLoading : This state is used to show and hide the ActivityIndicator when application start first time.

JSON_from_server : This is a State array used to store the JSON data coming from server.

fetching_Status : This state is used to show and hide the ActivityIndicator which shows inside the Loading Button.

this.page : This is a page parameter pass along with URL.

6. Create componentDidMount() method in your class, This is a inbuilt method and calls every time when application startup. We would call the server URL along with page number inside this function and parse the JSON.

7. Create fetch_more_data_from_server() function in your class, Inside this function we would again request for Web call and call the next 10 items from server by passing the Page number along with URL.

8. Create another function named as c, this function would render a horiontal Separator line between each FlatList item.

9. Create a function named as Render_Footer(), this function is used to render a View at the bottom of FlatList. Inside this view we would make a TouchableOpacity button which shows at the last of FlatList with Loading indicator.

10. Create a Root View inside render’s return block. Now inside this View we would make the FlatList component.

keyExtractor : Extract the unique key from FlatList.

data : Setting up the JSON data into FlatList.

ItemSeparatorComponent : Calling the ItemSeparatorComponent() function to render the separator line.

renderItem : Rendering the JSON items.

ListFooterComponent : Showing the footer view.

11. Create Style.

Screenshots in Android device:

Infinite List

Screenshots in iOS device:

18 Comments

  1. Online Franz Tech

    Hello,
    Love the tutorial, but how can I do that on scroll i.e, the user doesn’t press a button when he/she scroll down, it fetches!
    Thanks

    • Online Franz Tech

      i’ve figured it out alone

      Code this :

      import React, { Component } from ‘react’;
      import {
      AppRegistry, FlatList,
      Text, View, ActivityIndicator,
      StyleSheet, Platform,
      TouchableOpacity
      } from ‘react-native’;

      export default class FlatListFetch extends Component{

      constructor(props) {
      super(props);

      this.state = {
      isLoading: true,
      JSON_from_server: [],
      fetching_Status: false,
      }

      this.page = 0

      }

      componentDidMount()
      {
      this.page = this.page + 1;

      fetch(‘https://reactnativecode.000webhostapp.com/counting_table.php?page=’ + this.page)
      .then((response) => response.json())
      .then((responseJson) =>
      {
      this.setState({ JSON_from_server: [ …this.state.JSON_from_server, …responseJson ], isLoading: false });
      })
      .catch((error) =>
      {
      console.error(error);
      });
      }

      fetch_more_data_from_server =()=>
      {
      this.page = this.page + 1;

      this.setState({ fetching_Status: true }, () =>
      {
      fetch(‘https://reactnativecode.000webhostapp.com/counting_table.php?page=’ + this.page)
      .then((response) => response.json())
      .then((responseJson) =>
      {
      this.setState({ JSON_from_server: [ …this.state.JSON_from_server, …responseJson ], fetching_Status: false });
      })
      .catch((error) =>
      {
      console.error(error);
      });

      });

      }

      FlatListItemSeparator =()=> {
      return (

      );
      }

      render()
      {
      return(

      {
      ( this.state.isLoading )
      ?
      ( )
      :
      (
      index }

      data = { this.state.JSON_from_server }

      ItemSeparatorComponent = {this.FlatListItemSeparator}

      renderItem = {({ item, index }) => { item.value } }

      ListFooterComponent = { this.Render_Footer }
      refreshing = { this.state.fetching_Status}
      onRefresh = {this.fetch_more_data_from_server }
      onEndReached = {this.fetch_more_data_from_server}
      onEndThreshold = {100}
      />
      )
      }

      );
      }

      }

      const styles = StyleSheet.create(
      {
      MainContainer:
      {
      flex: 1,
      justifyContent: ‘center’,
      margin: 5,
      paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0
      },

      footerStyle:
      {
      padding: 7,
      alignItems: ‘center’,
      justifyContent: ‘center’,
      borderTopWidth: 2,
      borderTopColor: ‘#009688’
      },

      TouchableOpacity_style:
      {
      padding: 7,
      flexDirection: ‘row’,
      justifyContent: ‘center’,
      alignItems: ‘center’,
      backgroundColor: ‘#F44336’,
      borderRadius: 5,
      },

      TouchableOpacity_Inside_Text:
      {
      textAlign: ‘center’,
      color: ‘#fff’,
      fontSize: 18
      },

      flatList_items:
      {
      fontSize: 20,
      color: ‘#000’,
      padding: 10
      }
      });

  2. Thanks for the code.
    can you please tell us how to not showing (load more data from server) when there aren’t any data to load?

    • Samar, sorry i have not tried this yet, but if you figured it out. Post your code in comment so others can take benefit from your code.

  3. it worked for me and that’s my code.

    *************react native code*************

    import React, { Component } from ‘react’;

    import { StyleSheet, View, Text, Platform, FlatList, TouchableOpacity, ActivityIndicator } from ‘react-native’;

    export default class catigories extends Component {

    static navigationOptions =
    {

    };

    constructor()
    {
    super();

    this.state =
    {
    isLoading: true,
    JSON_from_server: [],
    fetching_Status: false,
    display:’flex’,
    }

    this.page = 0
    }

    OpenSecondActivity(id) {

    this.props.navigation.navigate(‘second’, { ListViewClickItemHolder: id });

    }

    OpenvideosActivity(id){
    this.props.navigation.navigate(’eman’, { ListViewClickItemHolder: id });
    }

    componentDidMount()
    {
    this.page = this.page + 1;

    fetch(‘http://arabscout.org/admin_arab/oldFiles/file.php?page=’ + this.page)
    .then((response) => response.json())
    .then((responseJson) =>
    {
    this.setState({ JSON_from_server: [ …this.state.JSON_from_server, …responseJson ], isLoading: false });
    })
    .catch((error) =>
    {
    console.error(error);
    });
    }
    fetch_more_data_from_server =()=>
    {
    this.page = this.page + 1;

    this.setState({ fetching_Status: true }, () =>
    {
    fetch(‘http://arabscout.org/admin_arab/oldFiles/file.php?page=’ + this.page)
    .then((response) => response.json())
    .then((responseJson) =>
    {
    this.setState({ JSON_from_server: [ …this.state.JSON_from_server, …responseJson ], fetching_Status: false });
    })
    .catch((error) =>
    {
    console.error(error);
    });

    });
    }
    FlatListItemSeparator =()=> {
    return (

    );
    }

    Render_Footer=()=>
    {
    return (

    {
    (this.state.JSON_from_server.includes(0) )
    ?

    Load More Data From Server
    {
    ( this.state.fetching_Status )
    ?

    :
    null
    }

    :

    Load More Data From Server
    {
    ( this.state.fetching_Status )
    ?

    :
    null
    }

    }

    )
    }

    render()
    {
    return(

    {
    ( this.state.isLoading )
    ?
    ( )
    :
    (
    index }

    data = { this.state.JSON_from_server }

    ItemSeparatorComponent = {this.FlatListItemSeparator}

    renderItem = {({ item, index }) => {if(item.sub_cat_count > 0){ return {item.value} ;}
    else if(item.sub_cat_count == 0){ return {item.value} ;}samar {item.num} }}

    ListFooterComponent = { this.Render_Footer }

    />
    )
    }

    );
    }
    }
    const styles = StyleSheet.create(
    {
    MainContainer:
    {
    flex: 1,
    justifyContent: ‘center’,
    margin: 5,
    paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0
    },

    footerStyle:
    {
    padding: 7,
    alignItems: ‘center’,
    justifyContent: ‘center’,
    borderTopWidth: 2,
    borderTopColor: ‘#009688’
    },

    TouchableOpacity_style:
    {
    padding: 7,
    flexDirection: ‘row’,
    justifyContent: ‘center’,
    alignItems: ‘center’,
    backgroundColor: ‘#F44336’,
    borderRadius: 5,
    },

    TouchableOpacity_Inside_Text:
    {
    textAlign: ‘center’,
    color: ‘#fff’,
    fontSize: 18
    },

    flatList_items:
    {
    fontSize: 20,
    color: ‘#000′,
    padding: 10
    },
    rowViewContainer: {
    fontSize: 20,
    width:’100%’,
    textAlignVertical:’center’,
    padding:10,
    color: ‘#a6ce39′,
    textAlign:’center’,
    margin:10

    },

    });

    ***************php code****************
    <?php
    include 'DBConfig.php';

    // Create connection
    $con = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
    mysqli_query($con,"SET NAMES utf8");
    mysqli_query($con,"SET CHARACTER SET utf8");
    // Getting page from URL.
    $page = $_GET['page'];

    // Show data from first row means 0 row.
    $start = 0;

    // Setting up data items limit, means it will only show only 10 items once.
    $stop = 3;

    // counting all the items present inside table.
    $all_rows = mysqli_num_rows(mysqli_query($con, "SELECT id from catigories"));

    $page_limit = ceil($all_rows/$stop);
    $num = 0;
    $res = array();
    // If page is more than the limit it will show a error message.
    if($page$row[‘id’], “value”=>$row[‘name’],”sub_cat_count”=>$row[‘sub_cat_count’]));
    }

    }
    if ($sqlnum>0){
    $json = json_encode($res); }
    else{

    array_push($res, $num);
    $json = json_encode($res);
    }
    echo $json ;
    $con->close();
    ?>

  4. hey is the a way to add search funtionality… searching from the database..

  5. Hi, may I know how to change the button of “load more data from server” into a list of button like pg 1, 2 , 3… like this

  6. How can one integrate Firebase so that one can fetch “children” from a Firebase-realtime-database?

  7. Thanks for your tutorial. For the frontend part, there’s a library, react-native-paginatable-list. I was using it for the pagination and infinite list in a few of my projects. https://www.npmjs.com/package/@twotalltotems/paginatable-list

Leave a Reply

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