Add Infinite Scroll in React App using React Infinite Scroller

Add Infinite Scroll in React App using React Infinite Scroller

Dead Simple Chat offers prebuilt Chat that can be added to any React or web app in minutes. It offers a powerful JavaScript Chat API and SDK and the ability to customize Chat UI.

In this blog post, we will go through the process of adding infinite scrolls into our React application using the React Infinite Scroller library.

React Infinite Scroller package has 3.1k starts on Github and was last updated 10 months ago. (As of the published date of this article).

What is Infinite Scroll?

If you are reading this blog post you must be familiar with infinite scroll, but if you don't know already, infinite scroll allows you dynamically load data as the. user scrolls.

Infinite scrolls are used in all social media applications and any app that shows the user a feed.

What is React Infinite Scroller?

React Infinite Scroller is an npm package that allows you easily add infinite scroll in your React Applications.

It also offers the ability to create infinite scrolls based on the window i.e the entire page or the creation of the infinite scroll as a child element. We will see examples of both in this blog post.

Let's start building with initializing the React application.

Building a React Infinite Scroll sample application

We will build a demo application using React infinite scroll. The demo application will dynamically load the feed item by calling a REST API to fetch the feed.

The demo will be similar to a real-world application where data is fetched from the API and loaded into the infinite scroller.

Initialize the React Application

To create a basic create application we will use the package create react app.

To use the create react app package, cd into a directory where you keep all your code and then run the command.

npx create-react-app react-infinite-scroll

Running this command will create a folder with the name react-infinite-scroll with the basic react application.

cd into the project directory by running the command cd react-infinite-scroll

Then run npm install to install the dependencies of the basic boilerplate react application.

Now run the command below to launch the application:

npm run start

The application will start at http://localhost:3000

In the next section, we will install some additional dependencies required for our project.

Install the dependencies

Stop the running program using Ctrl+c on Windows/Linux or CMD+c on Mac.

We will have to install react-infinite-scroller package to use in our project, and in the infinite scroll to load mock entries using axios package.

The required dependence includes:

  • axios

  • react-infinite-scroller

Run the command below to install the dependencies:

npm install --save axios react-infinite-scroller

Now we are ready to add infinite scroll into our React Application.

Adding Infinite Scroll

Open the App.js file and import the dependencies:

import InfiniteScroll from "react-infinite-scroller";
import axios from "axios";

Add the dependencies below the existing imports, for example:

import { useState } from "react";

import InfiniteScroll from "react-infinite-scroller";
import axios from "axios";

Update the App() function to include two state variables, items and page.

function App() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);

// ..<rest of the App() method

The items variable is used to store the items that we fetch from the API and the page variable is used to keep track of the page to load more items.

Fetching the data

We will use the https://jsonplaceholder.typicode.com/posts endpoint to fetch the mock data.

This API accepts _page and _limit query parameters. These parameters are useful for pagination.

Each time we fetch the list of items we will increment the _page value by 1.

We will create a fetchData() method. This method will be called automatically by our infinite scroll, when the user reaches the end of the list.

The fetchData() method will call the API, store the response in the items state and increment the value of page state variable by 1.

  const fetchData = async () => {
    const response = await axios.get(
      `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`
    );
    setItems([...items, ...response.data]);
    setPage(page + 1);
  };

Finally, we will add our InfiniteScroller

  return (
    <InfiniteScroll
      style={{ margin: "10px" }}
      pageStart={0}
      loadMore={fetchData}
      hasMore={true}
      loader={
        <div className="loader" key={0}>
          Loading ...
        </div>
      }
    >
      {items.map((item) => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.body}</p>
        </div>
      ))}
    </InfiniteScroll>
  );

Let's explain the options offered by the <InfiniteScroll> component:

style - This is the standard React attribute that is offered by this component and it allows us to set the style of the component. Here we are using the style attribute to add a margin of 10px.

pageStart - The pageStart indicate the initial page number to load. This value is passed to the fetchData method.

hasMore - This indicates if new items should be loaded when the user reaches the end of the scrollable area. Here we have set it to just true but we could also set this value dynamically in our fetchData method when no new items are available.

loader - loader is a special attribute, it allows you to specify a component to show when the Infinite Scroller is fetching the data. You can use it to show a loading icon or a spinner.

Here is the complete code of the App.js file:

import "./App.css";

import { useState } from "react";
import InfiniteScroll from "react-infinite-scroller";
import axios from "axios";

function App() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);

  const fetchData = async (__page) => {
    console.log(__page);
    const response = await axios.get(
      `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`
    );
    setItems([...items, ...response.data]);
    setPage(page + 1);
  };

  return (
    <InfiniteScroll
      style={{ margin: "10px" }}
      pageStart={0}
      loadMore={fetchData}
      hasMore={true}
      loader={
        <div className="loader" key={0}>
          Loading ...
        </div>
      }
    >
      {items.map((item) => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.body}</p>
        </div>
      ))}
    </InfiniteScroll>
  );
}

export default App;

Demo

Here is a demo of the infinite scroll application that we have built:

to watch the demo click on the demo link

Adding Infinite Scroll as Child Node

In the previous example, we added the infinite scroll as a parent component, but what if we wanted to add an infinite scroll as a child to a component of a fixed size.

In the next example, we will be doing exactly that.

Update the return of the App.js with the code below:

    <div>
      <h1>Infinite Scroll</h1>
      <div style={{ height: "500px", overflow: "auto" }}>
        <InfiniteScroll
          pageStart={0}
          loadMore={fetchData}
          hasMore={true}
          loader={
            <div className="loader" key={0}>
              Loading ...
            </div>
          }
          useWindow={false}
        >
          {items.map((item) => (
            <div key={item.id}>
              <h2>{item.title}</h2>
              <p>{item.body}</p>
            </div>
          ))}
        </InfiniteScroll>
      </div>
    </div>

In the above code snippet, we have encapsulated the InfiniteScroll inside a div.

We have set the height of the div to 500px

Now the important bit for the InfiniteScroll to work is to set the useWindow attribute of the InfiniteScroll to false

Here is the complete App.js code :

import "./App.css";

import { useState } from "react";
import InfiniteScroll from "react-infinite-scroller";
import axios from "axios";

function App() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);

  const fetchData = async (__page) => {
    console.log(__page);
    const response = await axios.get(
      `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`
    );
    setItems([...items, ...response.data]);
    setPage(page + 1);
  };

  return (
    <div>
      <h1>Infinite Scroll</h1>
      <div style={{ height: "500px", overflow: "auto" }}>
        <InfiniteScroll
          pageStart={0}
          loadMore={fetchData}
          hasMore={true}
          loader={
            <div className="loader" key={0}>
              Loading ...
            </div>
          }
          useWindow={false}
        >
          {items.map((item) => (
            <div key={item.id}>
              <h2>{item.title}</h2>
              <p>{item.body}</p>
            </div>
          ))}
        </InfiniteScroll>
      </div>
    </div>
  );
}

export default App;

Reversing the Scroller

The great thing about React Infinite Scrollers is that it can also be used in Reverse mode.

In the Reverse mode, the scroller will be scrolled up, rather than scroll down.

A reverse scroller is more suitable in Chat applications, where the user scrolls up to load the previous messages.

To use the scroller in Reverse Mode to be used in Chat application, then simply we need to set the isReverse to true.

Here is the code:

  return (
    <div>
      <h1>Infinite Scroll</h1>
      <div style={{ height: "500px", overflow: "auto" }}>
        <InfiniteScroll
          pageStart={0}
          loadMore={fetchData}
          hasMore={true}
          loader={
            <div className="loader" key={0}>
              Loading ...
            </div>
          }
          isReverse={true}
          useWindow={false}
        >
          {items.map((item) => (
            <div key={item.id}>
              <h2>{item.title}</h2>
              <p>{item.body}</p>
            </div>
          ))}
        </InfiniteScroll>
      </div>
    </div>
  );

Conclusion

In this blog post, we have learned how to use the React Infinite Scroller package and the options available in the Infinite Scroll component.

And we have built a sample application that calls the mock API to fetch the feed and display it in the infinite scroller.

We have also learned how to use the infinite scroll as a child component and in reverse mode.

Dead Simple Chat

Dead Simple Chat offers powerful JavaScript API and SDK that you can use to add chat in minutes to any React or web application.

Dead Simple Chat is dead simple to integrate, and our developer support team will assist you in integration if you need any help.

Signup for a free to account to try Dead Simple Chat which can be used for any chat usecase.

This article was originally published on the DeadSimpleChat blog: Add Infinite Scroll in React App using React Infinite Scroller