Skip to content
Source
Sign inSign up
TanStack/virtual
Open History to see the last commit

main.tsx

123 lines3.3 KB

1import './index.css'
2import * as React from 'react'
3import ReactDOM from 'react-dom'
4import { faker } from '@faker-js/faker'
5import { findIndex, groupBy } from 'lodash'
6import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual'
7import type { Range } from '@tanstack/react-virtual'
8​
9const groupedNames = groupBy(
10 Array.from({ length: 1000 })
11 .map(() => faker.person.firstName())
12 .sort(),
13 (name) => name[0],
15const groups = Object.keys(groupedNames)
16const rows = groups.reduce<Array<string>>(
17 (acc, k) => [...acc, k, ...groupedNames[k]],
18 [],
20​
21const App = () => {
22 const parentRef = React.useRef<HTMLDivElement>(null)
23​
24 const activeStickyIndexRef = React.useRef(0)
25​
26 const stickyIndexes = React.useMemo(
27 () => groups.map((gn) => findIndex(rows, (n) => n === gn)),
28 [],
29 )
30​
31 const isSticky = (index: number) => stickyIndexes.includes(index)
32​
33 const isActiveSticky = (index: number) =>
34 activeStickyIndexRef.current === index
35​
36 const rowVirtualizer = useVirtualizer({
37 count: rows.length,
38 estimateSize: () => 50,
39 getScrollElement: () => parentRef.current,
40 rangeExtractor: React.useCallback(
41 (range: Range) => {
42 activeStickyIndexRef.current =
43 [...stickyIndexes]
44 .reverse()
45 .find((index) => range.startIndex >= index) ?? 0
46​
47 const next = new Set([
48 activeStickyIndexRef.current,
49 ...defaultRangeExtractor(range),
50 ])
51​
52 return [...next].sort((a, b) => a - b)
53 },
54 [stickyIndexes],
55 ),
56 })
57​
58 return (
59 <div>
60 <div
61 ref={parentRef}
62 className="List"
63 style={{
64 height: `300px`,
65 width: `400px`,
66 overflow: 'auto',
67 }}
68 >
69 <div
70 style={{
71 height: `${rowVirtualizer.getTotalSize()}px`,
72 width: '100%',
73 position: 'relative',
74 }}
75 >
76 {rowVirtualizer.getVirtualItems().map((virtualRow) => (
77 <div
78 key={virtualRow.index}
79 className={'ListItem'}
80 style={{
81 ...(isSticky(virtualRow.index)
82 ? {
83 background: '#fff',
84 borderBottom: '1px solid #ddd',
85 zIndex: 1,
86 }
87 : {}),
88 ...(isActiveSticky(virtualRow.index)
89 ? {
90 position: 'sticky',
91 }
92 : {
93 position: 'absolute',
94 transform: `translateY(${virtualRow.start}px)`,
95 }),
96 top: 0,
97 left: 0,
98 width: '100%',
99 height: `${virtualRow.size}px`,
100 }}
101 >
102 {rows[virtualRow.index]}
103 </div>
104 ))}
105 </div>
106 </div>
107 {process.env.NODE_ENV === 'development' ? (
108 <p>
109 <strong>Notice:</strong> You are currently running React in
110 development mode. Rendering performance will be slightly degraded
111 until this application is built for production.
112 </p>
113 ) : null}
114 </div>
115 )
117​
118ReactDOM.render(
119 <React.StrictMode>
120 <App />
121 </React.StrictMode>,
122 document.getElementById('root'),