-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfiniteScrollUsingIntersectionObserver.tsx
More file actions
79 lines (71 loc) · 2.02 KB
/
Copy pathInfiniteScrollUsingIntersectionObserver.tsx
File metadata and controls
79 lines (71 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Use this inside react project
import React, { useEffect, useRef, useState, useCallback } from 'react';
const InfiniteScroll = () => {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const observerRef = useRef();
// Fake API call simulation
const fetchItems = async (page) => {
setLoading(true);
return new Promise((resolve) => {
setTimeout(() => {
const newItems = Array.from({ length: 10 }, (_, i) => `Item ${(page - 1) * 10 + i + 1}`);
resolve(newItems);
}, 1000);
});
};
// Load more items when page changes
useEffect(() => {
const load = async () => {
const newItems = await fetchItems(page);
setItems((prev) => [...prev, ...newItems]);
setLoading(false);
};
load();
}, [page]);
// Observer setup
const lastItemRef = useCallback(
(node) => {
if (loading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setPage((prev) => prev + 1);
}
});
if (node) observerRef.current.observe(node);
},
[loading]
);
return (
<div style={{ maxWidth: 400, margin: '0 auto' }}>
<h2>Infinite Scroll Demo</h2>
<ul>
{items.map((item, index) => {
if (index === items.length - 1) {
return (
<li
key={index}
ref={lastItemRef}
style={{ padding: '10px', border: '1px solid #ccc', marginBottom: '5px' }}
>
{item}
</li>
);
}
return (
<li
key={index}
style={{ padding: '10px', border: '1px solid #ccc', marginBottom: '5px' }}
>
{item}
</li>
);
})}
</ul>
{loading && <p>Loading more...</p>}
</div>
);
};
export default InfiniteScroll;