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.
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