Infinite Scroll
보통스크롤 시 자동으로 콘텐츠를 로드하는 무한 스크롤
라이브 데모
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
Item 7
Item 8
Item 9
Item 10
코드
InfiniteScroll.tsx
export const InfiniteScroll = () => {
const [items, setItems] = useState<number[]>(Array.from({ length: 10 }, (_, i) => i + 1));
const [isLoading, setIsLoading] = useState(false);
const loadMore = () => {
setIsLoading(true);
setTimeout(() => {
const newItems = Array.from({ length: 5 }, (_, i) => items.length + i + 1);
setItems([...items, ...newItems]);
setIsLoading(false);
}, 1000);
};
useEffect(() => {
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
if (scrollTop + clientHeight >= scrollHeight - 50) {
loadMore();
}
};
scrollElement?.addEventListener('scroll', handleScroll);
return () => scrollElement?.removeEventListener('scroll', handleScroll);
}, [items, isLoading]);
return (
<div className="infinite-scroll-container" ref={scrollRef}>
{items.map((item) => (
<div key={item}>Item {item}</div>
))}
{isLoading && <div>Loading...</div>}
</div>
);
};