The useLeafygreenTable hook is the recommended way to implement advanced table features. It wraps TanStack's react-table and react-virtual to provide styled support for features like virtualized scrolling, nested rows, and expandable rows.
When using this hook, you pass the returned table instance to the Table component and use the hook's methods (like getHeaderGroups() and getRowModel()) to render the UI components.
import {
Table,
TableHead,
HeaderRow,
TableBody,
Row,
Cell,
} from '@leafygreen-ui/table';
const tableContainerRef = React.useRef<HTMLDivElement>(null);
const data = React.useState(() => makeData(false, 10_000))[0];
const columns = React.useMemo<Array<ColumnDef<Person>>>(()
() => [
{ accessorKey: 'id', header: 'ID', size: 60 },
{ accessorKey: 'firstName', header: 'First Name', cell: info => info.getValue() },
],
[],
);
const table = useLeafygreenTable<Person>({
containerRef: tableContainerRef,
data,
columns,
});
const { rows } = table.getRowModel();
<Table
{...args}
table={table}
ref={tableContainerRef}
>
<TableHead>
{table.getHeaderGroups().map((headerGroup: HeaderGroup<Person>) => (
<HeaderRow key={headerGroup.id}>
{headerGroup.headers.map(header => (
<HeaderCell key={header.id} header={header}>
{flexRender(header.column.columnDef.header, header.getContext())}
</HeaderCell>
))}
</HeaderRow>
))}
</TableHead>
<TableBody>
{rows.map((row: LeafyGreenTableRow<Person>) => (
<Row key={row.id}>
{row.getVisibleCells().map((cell: LeafyGreenTableCell<Person>) => (
<Cell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</Cell>
))}
</Row>
))}
</TableBody>
</Table>