React Native FlatList Pagination to Load More Data dynamically – Infinite List

React Native FlatList Pagination

Here is an example of React Native FlatList Pagination to Load More Data dynamically – Infinite List. In this example, we will make a FlatList in which we will load the data in the form of pagination on a Click of a button. You can also visit Example of Infinite Loading Listview in React Native using FlatList for the infinite loading list view without load more button.

For those who don’t know what is pagination?

Let’s take a case where you can simply imagine what if Facebook loads all the Facebook posts from the Facebook database on your Facebook wall? Doesn’t it sound nasty? It will take hundreds of hours even more than that so what is the best way to load the data?  Simply paging. When you open Facebook they just show you 10-20 post and while you scroll the Facebook they load the next 10-20 posts in the background. That is what the paging is.

In our example,

  1. We are loading the first 10 posts from the web API call in componentDidMount.
  2. We have added load more button on the footer of the list.
  3. While clicking on the Load More Button we call the Web API again to get the next 10 posts.

We are using a variable offset to manage the index on upcoming Data. We will increase the offset by 1 after the successful call of the web API so that when we call the web API next time we will get the next dataset. So let’s get started with the example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Code for Pagination

Open App.js in any code editor and replace the code with the following code

App.js

//React Native FlatList Pagination to Load More Data dynamically – Infinite List
//https://aboutreact.com/react-native-flatlist-pagination-to-load-more-data-dynamically-infinite-list/

//import React in our code
import React, {useState, useEffect} from 'react';

//import all the components we are going to use
import {
  SafeAreaView,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  FlatList,
  ActivityIndicator,
} from 'react-native';

const App = () => {
  const [loading, setLoading] = useState(true);
  const [dataSource, setDataSource] = useState([]);
  const [offset, setOffset] = useState(1);

  useEffect(() => getData(), []);

  const getData = () => {
    console.log('getData');
    setLoading(true);
    //Service to get the data from the server to render
    fetch('https://abooutreactapis.000webhostapp.com/getpost.php?offset='
          + offset)
      //Sending the currect offset with get request
      .then((response) => response.json())
      .then((responseJson) => {
        //Successful response
        setOffset(offset + 1);
        //Increasing the offset for the next API call
        setDataSource([...dataSource, ...responseJson.results]);
        setLoading(false);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  const renderFooter = () => {
    return (
      //Footer View with Load More button
      <View style={styles.footer}>
        <TouchableOpacity
          activeOpacity={0.9}
          onPress={getData}
          //On Click of button load more data
          style={styles.loadMoreBtn}>
          <Text style={styles.btnText}>Load More</Text>
          {loading ? (
            <ActivityIndicator
              color="white"
              style={{marginLeft: 8}} />
          ) : null}
        </TouchableOpacity>
      </View>
    );
  };

  const ItemView = ({item}) => {
    return (
      // Flat List Item
      <Text
        style={styles.itemStyle}
        onPress={() => getItem(item)}>
        {item.id}
        {'.'}
        {item.title.toUpperCase()}
      </Text>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // Flat List Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    //Function for click on an item
    alert('Id : ' + item.id + ' Title : ' + item.title);
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <FlatList
          data={dataSource}
          keyExtractor={(item, index) => index.toString()}
          ItemSeparatorComponent={ItemSeparatorView}
          enableEmptySections={true}
          renderItem={ItemView}
          ListFooterComponent={renderFooter}
        />
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    flex: 1,
  },
  footer: {
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  loadMoreBtn: {
    padding: 10,
    backgroundColor: '#800000',
    borderRadius: 4,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnText: {
    color: 'white',
    fontSize: 15,
    textAlign: 'center',
  },
});

export default App;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

After Clicking on Load More It will load the data with the loader in Button

Output in Online Emulator

That was the React Native FlatList with Pagination to Load More Data dynamically. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

11 thoughts on “React Native FlatList Pagination to Load More Data dynamically – Infinite List”

  1. first this: this.offset = 0;
    second this: this.offset + 10;
    three this: this.offset + 10;

    10 is quantity itens per page.

    Very good, clean..

    Reply
  2. But this will increase the memory that your application is using on every fetch. The state will becoming larger and larger. Finally, the application will run out of memory. Am I wrong?

    Reply
  3. If we have fetched all the data after specific offset then how to remove the load more icon then? As all the data has been fetched then the load more button would not be necessary there.

    Reply
    • There can be many logics for that but what I usually do is while calling web service I have an idea how much data can come in a single call, for example, service will return 50 data sets in a single call so I make a logic to count the response and if it is 50 then I make the button state visible and if I get less no of data sets then I hide the button as this is the last set of the data. If you want to make the per call number dynamic you can ask your backend developer to send the max number of data set which can come in a single call.

      Reply
  4. Hello, great post.

    I have a question. How to do this without the button, just when you come to the end of the list, it will load the next offset?

    Thanks for the reply,

    Simon.

    Reply

Leave a Comment

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