Open History to see the last commit
1import * as React from 'react'
2import * as ReactDOM from 'react-dom/client'
3β
4import './index.css'
5β
6import { useWindowVirtualizer } from '@tanstack/react-virtual'
7β
8function Example() {
9 const listRef = React.useRef<HTMLDivElement | null>(null)
10 const listOffsetRef = React.useRef(0)
11β
12 React.useLayoutEffect(() => {
13 listOffsetRef.current = listRef.current?.offsetTop ?? 0
14 }, [])
15β
16 const virtualizer = useWindowVirtualizer({
17 count: 10000,
18 estimateSize: () => 35,
19 overscan: 5,
20 scrollMargin: listOffsetRef.current,
21 })
22β
23 return (
24 <>
25 <div ref={listRef} className="List">
26 <div
27 style={{
28 height: `${virtualizer.getTotalSize()}px`,
29 width: '100%',
30 position: 'relative',
31 }}
32 >
33 {virtualizer.getVirtualItems().map((item) => (
34 <div
35 key={item.key}
36 className={item.index % 2 ? 'ListItemOdd' : 'ListItemEven'}
37 style={{
38 position: 'absolute',
39 top: 0,
40 left: 0,
41 width: '100%',
42 height: `${item.size}px`,
43 transform: `translateY(${
44 item.start - virtualizer.options.scrollMargin
45 }px)`,
46 }}
47 >
48 Row {item.index}
49 </div>
50 ))}
51 </div>
52 </div>
53 </>
54 )
55}
56β
57function App() {
58 return (
59 <div>
60 <p>
61 In many cases, when implementing a virtualizer with a window as the
62 scrolling element, developers often find the need to specify a
63 "scrollMargin." The scroll margin is a crucial setting that defines the
64 space or gap between the start of the page and the edges of the list.
65 </p>
66 <br />
67 <br />
68 <h3>Window scroller</h3>
69 <Example />
70 <br />
71 <br />
72 {process.env.NODE_ENV === 'development' ? (
73 <p>
74 <strong>Notice:</strong> You are currently running React in
75 development mode. Rendering performance will be slightly degraded
76 until this application is built for production.
77 </p>
78 ) : null}
79 </div>
80 )
81}
82β
83ReactDOM.createRoot(document.getElementById('root')!).render(
84 <React.StrictMode>
85 <App />
86 </React.StrictMode>,
87)