React Infinite Scroll tutorial

React Infinite Scroll tutorial

In this tutorial, we are going to learn about how to implement infinite scroll in react by using react-infinite-scroll-component.

What is Infinite Scroll

Infinite Scroll helps us to load the data continuously when a user scrolls down the page.

Installing react infinite scroll

We are installing a new package called react-infinite-scroll-component which provides us a infinite scroll component.

Run the following command in your terminal to install the package.

npm i react-infinite-scroll-component

Example

This is a simple example of using react-infinite-scroll-component.

import React from "react";
import InfiniteScroll from "react-infinite-scroll-component";import axios from "axios";
import "./styles.css";

class App extends React.Component {
  state = {
    breweries: [],
    pageNumber: 1,
    items: 15,
    hasMore: true
  };

  componentDidMount() {
      //initial request is sent
    this.fetchData();
  }

  fetchData = () => {
    axios
      .get(
        `https://api.openbrewerydb.org/breweries?page=${
          this.state.pageNumber
        }&per_page=${this.state.items}`
      )
      .then(res =>
        this.setState({
          //updating data
          breweries: [...this.state.breweries, ...res.data],
          //updating page numbers
          pageNumber: this.state.pageNumber + 1
        })
      );
  };

  render() {
    return (
      <div className="App">
        <InfiniteScroll
          dataLength={this.state.breweries.length} //This is important field to render the next data          next={this.fetchData}          hasMore={this.state.hasMore}          loader={<h4>Loading...</h4>}        >
          {this.state.breweries.map(brewery => (
            <ul className="user" key={brewery.name}>
              <li>Name: {brewery.name}</li>
            </ul>
          ))}
        </InfiniteScroll>
      </div>
    );
  }
}

export default App;

In the above code, we first imported InfiniteScroll component from the package we just installed.

We passed four props to <InfiniteScroll> component which are datalength, next, hasMore, and loader.

  • dataLength: It takes the current data length.
  • next: It takes the fetch data method and invokes this method whenever a user reaches the bottom of a page.
  • hasMore: It takes the boolean value.
  • loader: It takes the loading spinner, which is rendered at the time of a api request is still in process.

react-infinite-scroll-example