"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Implementing infinite scrolling in react

Implementing infinite scrolling in react

Published on 2024-11-10
Browse:491

Implementing infinite scrolling in react

Before we start coding, if you want to know more about what pagination is and why do we need it, do check out my blog here.

Let's say the ask is to display 50 items on the screen and whenever user reaches to the bottom, load next 50 items.
For that we need to keep track of the scroll position and keep on comparing it with the document body offsetHeight.

To get the scroll position, we will use window.scrollY.
Basically window.scrollY gives the number of pixels the page has been scrolled vertically from the top. It tells you how far down the page the user has scrolled.
Along with the window.scrollY, we will be using two more values to check if the user has reached at the bottom of the page or not.
window.innerHeight: This represents the height of the visible part of the window (the viewport). It's the height of the area that the user can currently see in the browser without scrolling.

document.body.offsetHeight: It gives the total height of the body element.

Code:

import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
  let query = [];
  let [items, setitems] = useState(50);
  for (let i = 1; i {i});
  }

  useEffect(() => {
    const onScroll = () => {
      if (
        window.innerHeight   window.scrollY >=
        document.body.offsetHeight - 40
      ) {
        setitems(items   50);
      }
    };

    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, [items]);

  return 
{query.map((q) => q)}
; }

Explanation: The first render of the page will trigger the useEffect hook which will add a scroll event. Whenever scrolling event happens, onScroll() method will be invoked and the it will check the position of the scroll. If it is at the bottom-40, then more 50 items is added to the items state.

Release Statement This article is reproduced at: https://dev.to/aakash176/implementing-infinite-scrolling-in-react-4m2f?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3