-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualizedList.jsx
More file actions
37 lines (31 loc) · 1.05 KB
/
VirtualizedList.jsx
File metadata and controls
37 lines (31 loc) · 1.05 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
import React, { useEffect, useState } from 'react';
const VirtualizedList = ({ items }) => {
const [visibleItems, setVisibleItems] = useState([]);
const [scrollTop, setScrollTop] = useState(0);
const containerHeight = 500;
const itemHeight = 50;
useEffect(() => {
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = startIndex + Math.ceil(containerHeight / itemHeight);
setVisibleItems(items.slice(startIndex, endIndex));
}, [items, scrollTop]);
const handleScroll = (event) => {
setScrollTop(event.target.scrollTop);
};
return (
<div
className="virtualized-list"
style={{ height: `${containerHeight}px`, overflowY: 'scroll' }}
onScroll={handleScroll}
>
<div style={{ height: `${items.length * itemHeight}px`, position: 'relative' }}>
{visibleItems.map((item, index) => (
<div key={index} style={{ position: 'absolute', top: `${index * itemHeight}px` }}>
{item}
</div>
))}
</div>
</div>
);
};
export default VirtualizedList;