Skip to content

Instantly share code, notes, and snippets.

@dhanushkac
Last active January 22, 2023 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhanushkac/5bc3ebd274d33f7d0ac4cf4f1436d8a9 to your computer and use it in GitHub Desktop.
Save dhanushkac/5bc3ebd274d33f7d0ac4cf4f1436d8a9 to your computer and use it in GitHub Desktop.
Implement an infinite scroll using window height
import React, { useState, useEffect } from 'react';
const InfiniteScrollList = () => {
const [items, setItems] = useState([]);
useEffect(() => {
const loadMore = () => {
// fetch relavant data and update state
}
const handleScroll = () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loadMore();
}
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [items]);
return (
<div>
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}
</li>
))}
</ul>
</div>
);
};
export default InfiniteScrollList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment