React Infinite Scroll tutorial
In this post we will give you information about React Infinite Scroll tutorial. Hear we will give you detail about React Infinite Scroll tutorialAnd how to use it also give you demo for it if it is necessary.
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 ainfinite 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.
Hope this code and post will helped you for implement React Infinite Scroll tutorial. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs