To implement infinite scrolling in React, you can follow these steps:
Create a component for your list items that will be rendered on the page.
Set up a state to keep track of your list items and the page number.
Use the useEffect
hook to fetch the initial list items when the component mounts.
Create a function that will handle fetching more items when the user scrolls to the end of the list.
Add an event listener to detect when the user has scrolled to the bottom of the page.
Update the state with the new list items and increment the page number.
Render the updated list items on the page.
Here's an example code snippet of how you can implement infinite scrolling in React:
import React, { useState, useEffect } from 'react';
const InfiniteScroll = () => {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const response = await fetch(`https://api.example.com/items?page=${page}`);
const data = await response.json();
setItems([...items, ...data.items]);
};
const handleScroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [page]);
return (
<div>
{items.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default InfiniteScroll;
In this example, fetchData
is a function that fetches list items from an API and updates the state with the new items. handleScroll
is an event listener that detects when the user has scrolled to the bottom of the page and increments the page number to fetch more items. The list items are then rendered on the page using the map
function.