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

main.tsx

192 lines5.2 KB

1import * as React from 'react'
2import { createRoot } from 'react-dom/client'
3​
4import { useVirtualizer } from '@tanstack/react-virtual'
5import {
6 flexRender,
7 getCoreRowModel,
8 getSortedRowModel,
9 useReactTable,
10} from '@tanstack/react-table'
11import { makeData } from './makeData'
12import type { ColumnDef, Row, SortingState } from '@tanstack/react-table'
13import type { Person } from './makeData'
14import './index.css'
15​
16function ReactTableVirtualized() {
17 const [sorting, setSorting] = React.useState<SortingState>([])
18​
19 const columns = React.useMemo<Array<ColumnDef<Person>>>(
20 () => [
21 {
22 accessorKey: 'id',
23 header: 'ID',
24 size: 60,
25 },
26 {
27 accessorKey: 'firstName',
28 cell: (info) => info.getValue(),
29 },
30 {
31 accessorFn: (row) => row.lastName,
32 id: 'lastName',
33 cell: (info) => info.getValue(),
34 header: () => <span>Last Name</span>,
35 },
36 {
37 accessorKey: 'age',
38 header: () => 'Age',
39 size: 50,
40 },
41 {
42 accessorKey: 'visits',
43 header: () => <span>Visits</span>,
44 size: 50,
45 },
46 {
47 accessorKey: 'status',
48 header: 'Status',
49 },
50 {
51 accessorKey: 'progress',
52 header: 'Profile Progress',
53 size: 80,
54 },
55 {
56 accessorKey: 'createdAt',
57 header: 'Created At',
58 cell: (info) => info.getValue<Date>().toLocaleString(),
59 },
60 ],
61 [],
62 )
63​
64 const [data, setData] = React.useState(() => makeData(50_000))
65​
66 const table = useReactTable({
67 data,
68 columns,
69 state: {
70 sorting,
71 },
72 onSortingChange: setSorting,
73 getCoreRowModel: getCoreRowModel(),
74 getSortedRowModel: getSortedRowModel(),
75 debugTable: true,
76 })
77​
78 const { rows } = table.getRowModel()
79​
80 const parentRef = React.useRef<HTMLDivElement>(null)
81​
82 const virtualizer = useVirtualizer({
83 count: rows.length,
84 getScrollElement: () => parentRef.current,
85 estimateSize: () => 34,
86 overscan: 20,
87 })
88​
89 return (
90 <div ref={parentRef} className="container">
91 <div style={{ height: `${virtualizer.getTotalSize()}px` }}>
92 <table>
93 <thead>
94 {table.getHeaderGroups().map((headerGroup) => (
95 <tr key={headerGroup.id}>
96 {headerGroup.headers.map((header) => {
97 return (
98 <th
99 key={header.id}
100 colSpan={header.colSpan}
101 style={{ width: header.getSize() }}
102 >
103 {header.isPlaceholder ? null : (
104 <div
105 {...{
106 className: header.column.getCanSort()
107 ? 'cursor-pointer select-none'
108 : '',
109 onClick: header.column.getToggleSortingHandler(),
110 }}
111 >
112 {flexRender(
113 header.column.columnDef.header,
114 header.getContext(),
115 )}
116 {{
117 asc: ' πŸ”Ό',
118 desc: ' πŸ”½',
119 }[header.column.getIsSorted() as string] ?? null}
120 </div>
121 )}
122 </th>
123 )
124 })}
125 </tr>
126 ))}
127 </thead>
128 <tbody>
129 {virtualizer.getVirtualItems().map((virtualRow, index) => {
130 const row = rows[virtualRow.index]
131 return (
132 <tr
133 key={row.id}
134 style={{
135 height: `${virtualRow.size}px`,
136 transform: `translateY(${
137 virtualRow.start - index * virtualRow.size
138 }px)`,
139 }}
140 >
141 {row.getVisibleCells().map((cell) => {
142 return (
143 <td key={cell.id}>
144 {flexRender(
145 cell.column.columnDef.cell,
146 cell.getContext(),
147 )}
148 </td>
149 )
150 })}
151 </tr>
152 )
153 })}
154 </tbody>
155 </table>
156 </div>
157 </div>
158 )
160​
161function App() {
162 return (
163 <div>
164 <p>
165 For tables, the basis for the offset of the translate css function is
166 from the row's initial position itself. Because of this, we need to
167 calculate the translateY pixel count differently and base it off the
168 index.
169 </p>
170 <ReactTableVirtualized />
171 <br />
172 <br />
173 {process.env.NODE_ENV === 'development' ? (
174 <p>
175 <strong>Notice:</strong> You are currently running React in
176 development mode. Rendering performance will be slightly degraded
177 until this application is built for production.
178 </p>
179 ) : null}
180 </div>
181 )
183​
184const container = document.getElementById('root')
185const root = createRoot(container!)
186const { StrictMode } = React
187​
188root.render(
189 <StrictMode>
190 <App />
191 </StrictMode>,