Hello developer in this blog we are all gonna know about infinite-scroll
what exactly is an infinite scroll?
Infinite scroll is the mechanism that shows data based on an endless scroll event and loads data only as needed to avoid critical performance issues.
First of all, you have to install the following packages on your app.
npm install --save react-infinite-scroll-component or yarn add react-infinite-scroll-component
After installation successfully copy and paste this code into your app.js file and see the magic
Example:
import React, { useState } from "react"; import InfiniteScroll from "react-infinite-scroll-component"; const Infinitescroll = () => { const style = { height: 30, border: "1px solid green", margin: 6, padding: 8, }; const mainStyles = { // height: 200, position: "absolute", left: "35%", // top: "40%", width: "500px", height: "50vh", }; const [items, setItems] = useState(Array.from({ length: 20 })); const fetchData = () => { setTimeout(() => { setItems(items.concat(Array.from({ length: 20 }))); }, 1500); }; return ( <div style={mainStyles}> <h1 style={{ textAlign: "center" }}>Infinite Scroll</h1> <InfiniteScroll dataLength={items.length} //This is important field to render the next data next={fetchData} hasMore={true} loader={<h4>Loading...</h4>} > {items.map((i, index) => ( <div style={style} key={index}> div - #{index} </div> ))} </InfiniteScroll> </div> ); }; export default Infinitescroll;
Demo: