,

Infinite Scroll in React using react-infinite-scroll-component

Infinite scrolling data can be implemented in react js app by using the react-infinite-scroll-component library. We will create a sample application to demonstrate the Infinite scroll feature using the remote server. Infinite scrolling is a popular user interface design pattern used on modern web applications. It allows users to load more data as they scroll…

By.

min read

Infinite scrolling data can be implemented in react js app by using the react-infinite-scroll-component library. We will create a sample application to demonstrate the Infinite scroll feature using the remote server.

Infinite scrolling is a popular user interface design pattern used on modern web applications. It allows users to load more data as they scroll down the page or a container, rther than having to click on a “load more” button. React provides a great way to implement this pattern using the react-infinite-scroll-component package. In this tutorial, we will learn how to use this package to implement infinite scrolling in a React.js app. We will also create a mock JSON server to simulate the loading of data and display it in our app.

 

 

How to Add Infinite Scroll on List in React App?

Follow these steps to implement the load more feature or infinite scroll in react app:

Step 1 – Create React App
Step 2 – Install Required Libraries
Step 3 – Create Record Item Component
Step 4 – Create Record List Component
Step 5 – Using Record List in App
Step 6 – Setup JSON Server
Step 7 – Run the Application

 

Step 1 – Create React App

First let’s create a new react application by executing the below command:

npx create-react-app my-app

 

Step 2 – Install Required Libraries

Now, we will install the react-infinite-scroll-component to implement the infinite scroll feature and axios to make HTTP calls in React app.
Execute the following npm commands to install the required libraries:

npm install react-infinite-scroll-component axios

 

 

Step 3 – Create Record Item Component

To render each item of our list, we will create a new file RecordItem.js which will have the following component:

import React from "react";

const RecordItem = ({ record }) => {
  return (
    <div className="record-item">
      <h2>
        {record.id} -{record.title}
      </h2>
      <p>{record.description}</p>
      <p>Author: {record.author}</p>
      <p>Published: {record.published}</p>
    </div>
  );
};

export default RecordItem;

The RecordItem component accepts a record prop, which is an object containing the data for a single record. The component renders the title, description, author, and publication date for the record using JSX.

We will use this component within the upcomming RecordList component to display each record that is loaded from the JSON server.

 

Step 4 – Create Record List Component

Let’s create the RecordList.js file to have the Record List component and InfiniteScroll component that will create the infinite scrollable list for us.

import React, { useState, useEffect, useLayoutEffect } from "react";
import axios from "axios";
import RecordItem from "./RecordItem";
import InfiniteScroll from "react-infinite-scroll-component";

const RecordList = () => {
  const [records, setRecords] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  useLayoutEffect(() => {
    fetchRecords();
  }, []);

  const fetchRecords = async () => {
    console.log("fetchRecords");
    try {
      const response = await axios.get(
        `http://localhost:4000/records?_page=${page}&_limit=3`
      );
      const data = response.data;
      setRecords([...records, ...data]);
      setPage(page + 1);
      setHasMore(data.length > 0);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="record-list">
      <InfiniteScroll
        dataLength={records.length}
        next={fetchRecords}
        hasMore={hasMore}
        loader={<h4>Loading...</h4>}
      >
        {records.map((record) => (
          <RecordItem key={record.id} record={record} />
        ))}
      </InfiniteScroll>
    </div>
  );
};

export default RecordList;

The RecordList component fetches records from the JSON server using the axios library and the fetchRecords function. The component initalizes the state with an empty records array, a boolean hasMore variable, and a page variable that represents the current page of records.

The useEffect hook is used to fetch the initial records when the component mounts. The fetchRecords function fetches 10 records at a time using the _page and _limit query paramters, and adds them to the records state using the spread operator. The function also updates the page state and checks whether there are more records to fetch by checking the length of the returned data.

The component renders an InfiniteScroll component from the react-infinite-scroll-component library, which takes care of triggering the fetchRecords function when the user scrolls to the bottom of the page. The hasMore prop is set to the hasMore state variable, which determins whether there are more records to fetch. The loader prop specifies a loading message to display while records are being fetched.

Finally, the RecordList component maps over the records state and renders a RecordItem component for each record, passing the record data as a prop.

We will be using this component in our App component to display a scrollable list of records fetched from a JSON server.

 

Step 5 – Using Record List in App

Thereafter, open the App.js file and update it as shown below to include out RecordList component:

import React from "react";
import RecordList from "./RecordList";

const App = () => {
  return (
    <div className="App">
      <h1>Infinite Scroll List in React App - FreakyJolly.com</h1>
      <RecordList />
    </div>
  );
};

export default App;

 

Step 6 – Set up a mock JSON server

Now we will set up our mock server to load responses from a db.json file.

Install the json-server package globally by executing below command:

npm install -g json-server

Create a db.json file with some sample data as shown below at the application root.

{
  "records": [
    {
      "id": 1,
      "title": "The Catcher in the Rye",
      "description": "A story about a teenager named Holden Caulfield who is kicked out of his prep school and wanders the streets of New York City.",
      "author": "J.D. Salinger",
      "published": "1951"
    },
    {
      "id": 2,
      "title": "To Kill a Mockingbird",
      "description": "A story about a young girl named Scout Finch who lives in a small Alabama town during the Great Depression and learns about racial injustice.",
      "author": "Harper Lee",
      "published": "1960"
    },
    {
      "id": 3,
      "title": "The Great Gatsby",
      "description": "A story about a wealthy man named Jay Gatsby who tries to win back his lost love by throwing extravagant parties.",
      "author": "F. Scott Fitzgerald",
      "published": "1925"
    },
    {
      "id": 4,
      "title": "1984",
      "description": "A story about a totalitarian society where individuality and freedom are suppressed.",
      "author": "George Orwell",
      "published": "1949"
    },
    {
      "id": 5,
      "title": "Pride and Prejudice",
      "description": "A story about the romantic relationship between Elizabeth Bennet and Mr. Darcy in Georgian England.",
      "author": "Jane Austen",
      "published": "1813"
    },
    {
      "id": 6,
      "title": "The Lord of the Rings",
      "description": "A fantasy epic about a hobbit named Frodo Baggins who embarks on a quest to destroy the One Ring and defeat the Dark Lord Sauron.",
      "author": "J.R.R. Tolkien",
      "published": "1954"
    },
    {
      "id": 7,
      "title": "The Hobbit",
      "description": "A children's fantasy about a hobbit named Bilbo Baggins who joins a company of dwarves on a quest to reclaim their stolen treasure.",
      "author": "J.R.R. Tolkien",
      "published": "1937"
    },
    {
      "id": 8,
      "title": "The Adventures of Huckleberry Finn",
      "description": "A story about a young boy named Huck Finn who escapes from his abusive father and embarks on a journey down the Mississippi River with a runaway slave named Jim.",
      "author": "Mark Twain",
      "published": "1884"
    },
    {
      "id": 9,
      "title": "The Grapes of Wrath",
      "description": "A story about a family of tenant farmers who are forced to migrate from Oklahoma to California during the Great Depression.",
      "author": "John Steinbeck",
      "published": "1939"
    },
    {
      "id": 10,
      "title": "One Hundred Years of Solitude",
      "description": "A magical realist novel about the Buendía family and their struggles over the course of seven generations in the fictional town of Macondo.",
      "author": "Gabriel García Márquez",
      "published": "1967"
    }
  ]
}

Now start the server by executing the below command and run it at port 4000:

json-server --watch db.json --port 4000

Step 7 – Run the Application

As our JSON server is running, now lets run the React application by executing npm start.

 

How to Load Items on Container Scroll Instead of Page scroll for Infinite Scroll?

By default the Infinite Scroll looks for scroll event on page scroll event handler so the items which are directly placed into the page will work as expected in such scenerios.

But in case, where we need to have child containers to leverage the feature of infinite scroll, we need to look for scroll events on the container rather than the page. For that we need to add the scrollableTarget prop with the respective id on div container as shown below:

<div className="record-list" id="scrollEle">
      <InfiniteScroll
        dataLength={records.length}
        next={fetchRecords}
        hasMore={hasMore}
        loader={<h4>Loading...</h4>}
        scrollableTarget="scrollEle"
      >
        {records.map((record) => (
          <RecordItem key={record.id} record={record} />
        ))}
      </InfiniteScroll>
    </div>

Conclusion

You have successfully created a sample application that uses infinite scroll to fetch data from a mock JSON server. With infinite scroll, you have achieved a smoother user experience by dynamicaly loading data as the user scrolls through the page, rather than loading all the data upfront.

By using React and its hooks, such as useState and useEffect, you were able to create a functional and responsive UI with minimum code. You have also learned how to crete reusable components and container components to keep your code organized and maintainable.

In addition, you have also learned how to set up a mock JSON server using the json-server package, allowing you to easily and quickly create a REST API to mock your data. This can be especially useful for testing and development purposes.

Overall, infinite scroll is a great feature to add to your applications, and with the skills you have learned here, you can now implement it in your own projcts. So go ahead, and create something amazing!

Leave a Reply

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