Infinite Scroll: Seamless Content Loading using React JS
npm install infinite-scrolling-js HTML
const apiCall = () => {
axios({
method: "",
url: "",
params: {},
})
.then((res) => {
setrecords((prevrecords) => {
return [
...new Set([...prevrecords, ...res.data.docs.map((b) => b.title)]),
];
});
// hasMore: Indicates whether there are more total values than the current offset records. If this is set to false, even when reaching the last element, the callbackAPI will not be triggered.
setHasMore(res.data.totalDocs > res.data.docs.length);
})
.catch((error) => {});
};
const { lastElementRef } = useInfiniteScroll(
pageNumber,
setPageNumber,
hasMore,
apiCall,
records
);
pageNumber: A state variable representing the current page number, managed by useState.
setPageNumber: A function to set the current page number.
hasMore: A boolean value indicating whether there is a next offset available.
apiCall: A function triggered when scrolling reaches the end of the content.
records: A state variable representing the current offset records, managed by useState
{records.map((record, index) => {
if (records.length === index + 1) {
return (
// adding a ref to the last element
{record}
);
} else {
return {record};
}
})}
``