Home  >  Article  >  Web Front-end  >  Implementing infinite scrolling in react

Implementing infinite scrolling in react

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-10 06:25:291061browse

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 <= items; i++) {
    query.push(<p>{i}</p>);
  }

  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 <div className="App">{query.map((q) => q)}</div>;
}

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.

The above is the detailed content of Implementing infinite scrolling in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:async / awaitNext article:async / await