-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathmain.tsx
More file actions
259 lines (244 loc) · 6.96 KB
/
main.tsx
File metadata and controls
259 lines (244 loc) · 6.96 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import {
useReactTable,
getCoreRowModel,
ColumnDef,
flexRender,
Table,
} from '@tanstack/react-table'
import { makeData } from './makeData'
type Person = {
firstName: string
lastName: string
age: number
visits: number
status: string
progress: number
}
const defaultColumns: ColumnDef<Person>[] = [
{
header: 'Name',
footer: props => props.column.id,
columns: [
{
accessorKey: 'firstName',
cell: info => info.getValue(),
footer: props => props.column.id,
},
{
accessorFn: row => row.lastName,
id: 'lastName',
cell: info => info.getValue(),
header: () => <span>Last Name</span>,
footer: props => props.column.id,
},
],
},
{
header: 'Info',
footer: props => props.column.id,
columns: [
{
accessorKey: 'age',
header: () => 'Age',
footer: props => props.column.id,
},
{
accessorKey: 'visits',
header: () => <span>Visits</span>,
footer: props => props.column.id,
},
{
accessorKey: 'status',
header: 'Status',
footer: props => props.column.id,
},
{
accessorKey: 'progress',
header: 'Profile Progress',
footer: props => props.column.id,
},
],
},
]
function App() {
const [data, _setData] = React.useState(() => makeData(200))
const [columns] = React.useState<typeof defaultColumns>(() => [
...defaultColumns,
])
const rerender = React.useReducer(() => ({}), {})[1]
const table = useReactTable({
data,
columns,
defaultColumn: {
minSize: 60,
maxSize: 800,
},
columnResizeMode: 'onChange',
getCoreRowModel: getCoreRowModel(),
debugTable: true,
debugHeaders: true,
debugColumns: true,
})
/**
* Instead of calling `column.getSize()` on every render for every header
* and especially every data cell (very expensive),
* we will calculate all column sizes at once at the root table level in a useMemo
* and pass the column sizes down as CSS variables to the <table> element.
*/
const columnSizeVars = React.useMemo(() => {
const headers = table.getFlatHeaders()
const colSizes: { [key: string]: number } = {}
for (let i = 0; i < headers.length; i++) {
const header = headers[i]!
colSizes[`--header-${header.id}-size`] = header.getSize()
colSizes[`--col-${header.column.id}-size`] = header.column.getSize()
}
return colSizes
}, [table.getState().columnSizingInfo, table.getState().columnSizing])
//demo purposes
const [enableMemo, setEnableMemo] = React.useState(true)
return (
<div className="p-2">
<i>
This example has artificially slow cell renders to simulate complex
usage
</i>
<div className="h-4" />
<label>
Memoize Table Body:{' '}
<input
type="checkbox"
checked={enableMemo}
onChange={() => setEnableMemo(!enableMemo)}
/>
</label>
<div className="h-4" />
<button onClick={() => rerender()} className="border p-2">
Rerender
</button>
<pre style={{ minHeight: '10rem' }}>
{JSON.stringify(
{
columnSizing: table.getState().columnSizing,
},
null,
2
)}
</pre>
<div className="h-4" />({data.length} rows)
<div className="overflow-x-auto">
{/* Here in the <table> equivalent element (surrounds all table head and data cells), we will define our CSS variables for column sizes */}
<div
{...{
className: 'divTable',
style: {
...columnSizeVars, //Define column sizes on the <table> element
width: table.getTotalSize(),
},
}}
>
<div className="thead">
{table.getHeaderGroups().map(headerGroup => (
<div
{...{
key: headerGroup.id,
className: 'tr',
}}
>
{headerGroup.headers.map(header => (
<div
{...{
key: header.id,
className: 'th',
style: {
width: `calc(var(--header-${header?.id}-size) * 1px)`,
},
}}
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
<div
{...{
onDoubleClick: () => header.column.resetSize(),
onMouseDown: header.getResizeHandler(),
onTouchStart: header.getResizeHandler(),
className: `resizer ${
header.column.getIsResizing() ? 'isResizing' : ''
}`,
}}
/>
</div>
))}
</div>
))}
</div>
{/* When resizing any column we will render this special memoized version of our table body */}
{enableMemo ? (
<MemoizedTableBody table={table} />
) : (
<TableBody table={table} />
)}
</div>
</div>
</div>
)
}
//un-memoized normal table body component - see memoized version below
function TableBody({ table }: { table: Table<Person> }) {
return (
<div
{...{
className: 'tbody',
}}
>
{table.getRowModel().rows.map(row => (
<div
{...{
key: row.id,
className: 'tr',
}}
>
{row.getVisibleCells().map(cell => {
//simulate expensive render
for (let i = 0; i < 10000; i++) {
Math.random()
}
return (
<div
{...{
key: cell.id,
className: 'td',
style: {
width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
},
}}
>
{cell.renderValue<any>()}
</div>
)
})}
</div>
))}
</div>
)
}
//special memoized wrapper for our table body that we will use during column resizing
export const MemoizedTableBody = React.memo(TableBody, (prev, next) =>
next.table.getState().columnSizingInfo.isResizingColumn
? prev.table.options.data === next.table.options.data
: false
) as typeof TableBody
const rootElement = document.getElementById('root')
if (!rootElement) throw new Error('Failed to find the root element')
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
)