-
-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathmain.tsx
More file actions
90 lines (84 loc) · 2.18 KB
/
main.tsx
File metadata and controls
90 lines (84 loc) · 2.18 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
80
81
82
83
84
85
86
87
88
89
90
import React from 'react'
import ReactDOM from 'react-dom/client'
import { useHook as useVirtualizer } from '../useHook'
function getRandomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
const randomHeight = (() => {
const cache = new Map()
return (id: string) => {
const value = cache.get(id)
if (value !== undefined) {
return value
}
const v = getRandomInt(25, 100)
cache.set(id, v)
return v
}
})()
const App = () => {
const parentRef = React.useRef<HTMLDivElement>(null)
const rowVirtualizer = useVirtualizer({
count: 1002,
getScrollElement: () => parentRef.current,
estimateSize: () => 50,
debug: true,
})
return (
<div>
<button
id="scroll-to-1000"
onClick={() => rowVirtualizer.scrollToIndex(1000)}
>
Scroll to 1000
</button>
<button
id="scroll-to-last"
onClick={() => rowVirtualizer.scrollToIndex(1001)}
>
Scroll to last
</button>
<button id="scroll-to-0" onClick={() => rowVirtualizer.scrollToIndex(0)}>
Scroll to 0
</button>
<div
ref={parentRef}
id="scroll-container"
style={{
height: 400,
overflow: 'auto',
contain: 'strict',
overflowAnchor: 'none',
}}
>
<div
style={{
height: rowVirtualizer.getTotalSize(),
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
data-testid={`item-${v.index}`}
ref={rowVirtualizer.measureElement}
data-index={v.index}
style={{
position: 'absolute',
top: 0,
left: 0,
transform: `translateY(${v.start}px)`,
width: '100%',
}}
>
<div style={{ height: randomHeight(String(v.key)) }}>
Row {v.index}
</div>
</div>
))}
</div>
</div>
</div>
)
}
ReactDOM.createRoot(document.getElementById('root')!).render(<App />)