import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import {
ColumnDef,
flexRender,
getCoreRowModel,
getSortedRowModel,
Row,
Table,
useReactTable,
} from '@tanstack/react-table'
import {
useVirtualizer,
VirtualItem,
Virtualizer,
} from '@tanstack/react-virtual'
import { makeData, Person } from './makeData'
function App() {
const columns = React.useMemo<ColumnDef<Person>[]>(
() => [
{
accessorKey: 'id',
header: 'ID',
size: 60,
},
{
accessorKey: 'firstName',
cell: (info) => info.getValue(),
},
{
accessorFn: (row) => row.lastName,
id: 'lastName',
cell: (info) => info.getValue(),
header: () => <span>Last Name</span>,
},
{
accessorKey: 'age',
header: () => 'Age',
size: 50,
},
{
accessorKey: 'visits',
header: () => <span>Visits</span>,
size: 50,
},
{
accessorKey: 'status',
header: 'Status',
},
{
accessorKey: 'progress',
header: 'Profile Progress',
size: 80,
},
{
accessorKey: 'createdAt',
header: 'Created At',
cell: (info) => info.getValue<Date>().toLocaleString(),
size: 250,
},
],
[],
)
const tableContainerRef = React.useRef<HTMLDivElement>(null)
const [data, setData] = React.useState(() => makeData(50_000))
const refreshData = React.useCallback(() => {
setData(makeData(50_000))
}, [])
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
debugTable: true,
})
return (
<div className="app">
{process.env.NODE_ENV === 'development' ? (
<p>
<strong>Notice:</strong> You are currently running React in
development mode. Virtualized rendering performance will be slightly
degraded until this application is built for production.
</p>
) : null}
({data.length} rows)
<button onClick={refreshData}>Refresh Data</button>
<div
className="container"
ref={tableContainerRef}
style={{
overflow: 'auto',
position: 'relative',
height: '800px',
}}
>
{}
<table style={{ display: 'grid' }}>
<thead
style={{
display: 'grid',
position: 'sticky',
top: 0,
zIndex: 1,
}}
>
{table.getHeaderGroups().map((headerGroup) => (
<tr
key={headerGroup.id}
style={{ display: 'flex', width: '100%' }}
>
{headerGroup.headers.map((header) => {
return (
<th
key={header.id}
style={{
display: 'flex',
width: header.getSize(),
}}
>
<div
{...{
className: header.column.getCanSort()
? 'cursor-pointer select-none'
: '',
onClick: header.column.getToggleSortingHandler(),
}}
>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
{{
asc: ' 🔼',
desc: ' 🔽',
}[header.column.getIsSorted() as string] ?? null}
</div>
</th>
)
})}
</tr>
))}
</thead>
<TableBody table={table} tableContainerRef={tableContainerRef} />
</table>
</div>
</div>
)
}
interface TableBodyProps {
table: Table<Person>
tableContainerRef: React.RefObject<HTMLDivElement>
}
function TableBody({ table, tableContainerRef }: TableBodyProps) {
const { rows } = table.getRowModel()
const rowVirtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({
count: rows.length,
estimateSize: () => 33,
getScrollElement: () => tableContainerRef.current,
measureElement:
typeof window !== 'undefined' &&
navigator.userAgent.indexOf('Firefox') === -1
? (element) => element?.getBoundingClientRect().height
: undefined,
overscan: 5,
})
return (
<tbody
style={{
display: 'grid',
height: `${rowVirtualizer.getTotalSize()}px`,
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
const row = rows[virtualRow.index] as Row<Person>
return (
<TableBodyRow
key={row.id}
row={row}
virtualRow={virtualRow}
rowVirtualizer={rowVirtualizer}
/>
)
})}
</tbody>
)
}
interface TableBodyRowProps {
row: Row<Person>
virtualRow: VirtualItem
rowVirtualizer: Virtualizer<HTMLDivElement, HTMLTableRowElement>
}
function TableBodyRow({ row, virtualRow, rowVirtualizer }: TableBodyRowProps) {
return (
<tr
data-index={virtualRow.index}
ref={(node) => rowVirtualizer.measureElement(node)}
key={row.id}
style={{
display: 'flex',
position: 'absolute',
transform: `translateY(${virtualRow.start}px)`,
width: '100%',
}}
>
{row.getVisibleCells().map((cell) => {
return (
<td
key={cell.id}
style={{
display: 'flex',
width: cell.column.getSize(),
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
)
})}
</tr>
)
}
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>,
)