Creating infinite loading & Scrolling in ReactJs

Total
0
Shares
infinite loading in reactjs using react-infinite-scroll-component

Introduction

Many applications use the infinite scroll functionality to display large number of records. For example, when you browse through the products on ecommerce like Amazon.com, you either get the pagination or infinite loading. Since the records are huge in number so they can’t be displayed all at once. It is therefore necessary to implement an infinite loading.

In order to apply the functionality, you need to use the react-infinite-scroll-component. Below we will take you through how to implement the component and finally explore the feature in the Reactjs application.

Getting Started with Infinite Scrolling

Install or add react infinite scroll component to your React application.

npm install --save react-infinite-scroll-component

or

yarn add react-infinite-scroll-component

If you do not have the data you require for testing the component, you can apply the simple div example that you will see in our live demo. You can also go ahead and utilize the free APIs set for such demonstrations. Such APIs include NASA’s Astronomy Picture of the Day (APOD) API,  THE RESTFUL POKEMON API, etc.

Infinite scrolling will require two key parts –

  1. Check for the window scroll position to determine if a user has reached the bottom of the page.
  2. Handling the request for additional information to display.

From here you can add an initial load and any error handling measures that should occur during the loading process.

The react-infinite-scroll-component will provide you the InfiniteScroll component. It works in this way –

  1. Specifing a value for the height prop if you want your scrollable content to have a specific height.
  2. Providing scrollbars for scrolling your content.
  3. Fetching more data.

If your scrollable content is being rendered within a parent element that is already providing overflow scrollbars, you can set the scrollableTarget prop to reference the DOM element and use its scrollbars for fetching more data.

Without setting either the height or scrollableTarget props, the scroll will happen at document.body like Facebook’s timeline scroll.

In the example below we have implemented the document.body InfiniteScroll property.

Code Example

//scroll.jsx

import React from "react";
import InfiniteScroll from "react-infinite-scroll-component";

const style = {
  height: 30,
  border: "3px solid pink",
  margin: 6,
  padding: 8
};

class Scroll extends React.Component {
  state = {
    items: Array.from({ length: 20 })
  };

  fetchMoreData = () => {

    setTimeout(() => {
      this.setState({
        items: this.state.items.concat(Array.from({ length: 20 }))
      });
    }, 1500);
  };

  render() {
    return (
      <div>
        <InfiniteScroll
          dataLength={this.state.items.length}
          next={this.fetchMoreData}
          hasMore={true}
          loader={<h4>Loading...</h4>}
        >
          {this.state.items.map((i, index) => (
            <div style={style} key={index}>
              div - {index}
            </div>
          ))}
        </InfiniteScroll>
      </div>
    );
  }
}

export default Scroll;
//App.js

import React from "react";
import Scroll from "./scroll";

export default function App() {
  return (
    <div className="App">
      <h1>React infinite scroll example</h1>
      <hr />
      <Scroll />
    </div>
  );
}

In the scroll.jsx file above

We created a new child component called scroll.jsx and created a state object of our div with its properties.

Next, we added a function, fetchMoreData() that is called each time we want to load the next page record of items. The items will be in sets of 20s in a 1.5 s timeline.

The fetch function is able to call our API to get new data it’s triggered by the <InfiniteScroll/> component when we scroll to the end of the view, there is a count variable we use to monitor the page loaded and it is incremented after the data is loaded.

React effect is used to load the first batch of data into the view. We pass the systems function and the items variable into the function.

With that, we export the scroll.jsx file to the app.js file and then re-run the app.

Our divs appear in groups of 20 with the loading more feature appearing for a second as the items are featured.

      This is the best article on infinite loading in ReactJs ♥♥

Click here to Tweet this

Live Demo

If live demo fails to load properly on the website then please use the below button to open it in separate tab.

Open Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like