Table
Show structured data in rows and columns, with optional sorting, row selection, pagination and bulk actions.
@volvo-cars/react-table gives you the table parts: a styled React component for each table element, and controls for sorting, pagination and bulk actions. It doesn’t keep track of table state. For sorting, row selection, pagination and similar behavior, pair it with TanStack Table 9, a headless library that handles the logic and renders nothing.
Show code
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from '@volvo-cars/react-table';
const cars = [ { model: 'EX30', powertrain: 'Electric', inStock: 14, onOrder: 32 }, { model: 'XC60', powertrain: 'Plug-in hybrid', inStock: 9, onOrder: 21 }, { model: 'EX90', powertrain: 'Electric', inStock: 3, onOrder: 18 },];
export function TableBasic() { return ( <Table aria-label="Cars in stock"> <TableHeader> <TableRow> <TableHead>Model</TableHead> <TableHead>Powertrain</TableHead> <TableHead>In stock</TableHead> <TableHead>On order</TableHead> </TableRow> </TableHeader> <TableBody> {cars.map((car) => ( <TableRow key={car.model}> <TableCell>{car.model}</TableCell> <TableCell>{car.powertrain}</TableCell> <TableCell>{car.inStock}</TableCell> <TableCell>{car.onOrder}</TableCell> </TableRow> ))} </TableBody> </Table> );}How it works with TanStack Table
Section titled “How it works with TanStack Table”TanStack Table decides which rows and columns to show, and tracks sorting, selection, expanded rows and pages. @volvo-cars/react-table renders the result with design system styles.
| Your table needs | Use |
|---|---|
| Static rows, or data you’ve already sorted and paged | The parts. Map over your data; you don’t write any TanStack code. |
| Sorting, filtering, row selection, pagination, sub-rows or resizable columns | A TanStack table from useTable, rendered with the parts or with SimpleTable. |
| No React | The table class from @volvo-cars/css. See CSS. |
Only SimpleTable and SimplePagination take a TanStack table. Every other component takes plain props, so you can drive it from TanStack Table or from your own state. For example, Sortable takes isSorted and onClick, and PaginationPageSelect takes value, totalPages and onChange.
Installation
Section titled “Installation”@volvo-cars/react-table needs @volvo-cars/css 3.2 or later and @tanstack/react-table 9.1.2 or later. It doesn’t need @volvo-cars/edls-css.
yarn add @volvo-cars/react-table @tanstack/react-tableInstall @tanstack/react-table even if you only use the parts. @volvo-cars/react-table imports it, so your build fails without it. It uses your copy, so your tables and the components share the same version.
Anatomy
Section titled “Anatomy”Each part renders one HTML element and accepts that element’s props. A className you pass merges with the part’s own classes.
| Component | Renders |
|---|---|
Table |
<table class="table">, full width, 14px text |
TableCaption |
<caption> |
TableHeader |
<thead> |
TableBody |
<tbody> |
TableFooter |
<tfoot> |
TableRow |
<tr> |
TableHead |
<th>, with header text that wraps |
TableCell |
<td> |
The controls have their own sections: Sortable, ResizeHandle, the pagination parts and the action bar parts.
Rendering a TanStack table
Section titled “Rendering a TanStack table”Create the table with useTable and pass it to SimpleTable. It renders the headers and the visible cells of every row, and applies each column’s meta.className and meta.style to its cells. It also marks selected rows with aria-selected and sub-rows with data-nested. Other props, such as aria-label, go to the <table> element.
Show code
import { type ColumnDef, tableFeatures, useTable } from '@tanstack/react-table';import { SimpleTable } from '@volvo-cars/react-table';
type Car = { model: string; powertrain: string; inStock: number; onOrder: number;};
const features = tableFeatures({});
const data: Car[] = [ { model: 'EX30', powertrain: 'Electric', inStock: 14, onOrder: 32 }, { model: 'XC60', powertrain: 'Plug-in hybrid', inStock: 9, onOrder: 21 }, { model: 'EX90', powertrain: 'Electric', inStock: 3, onOrder: 18 },];
const columns: ColumnDef<typeof features, Car>[] = [ { accessorKey: 'model', header: 'Model' }, { accessorKey: 'powertrain', header: 'Powertrain' }, { accessorKey: 'inStock', header: 'In stock' }, { accessorKey: 'onOrder', header: 'On order' },];
export function TableSimple() { const table = useTable({ features, columns, data });
return <SimpleTable table={table} aria-label="Cars in stock" />;}Register only the features a table uses with tableFeatures. Render the parts yourself when you need more control over headers, rows or cells, as the examples do.
SimpleTable and SimplePagination update when the state selected by useTable changes, which by default is all of it. If you pass useTable a selector, include the state they show, such as sorting, rowSelection, expanded and pagination.
Add the table class to a <table>. It styles the th, tr and td elements inside it. Header text stays on one line; add text-wrap to a th to let it wrap, as TableHead does.
Show code
<table class="table w-full font-14" aria-label="Cars in stock"> <thead> <tr> <th class="text-wrap">Model</th> <th class="text-wrap">Powertrain</th> <th class="text-wrap">In stock</th> <th class="text-wrap">On order</th> </tr> </thead> <tbody> <tr> <td>EX30</td> <td>Electric</td> <td>14</td> <td>32</td> </tr> <tr> <td>XC60</td> <td>Plug-in hybrid</td> <td>9</td> <td>21</td> </tr> <tr> <td>EX90</td> <td>Electric</td> <td>3</td> <td>18</td> </tr> </tbody></table>States
Section titled “States”Add these classes to rows:
odd:bg-secondarystripes every other row.hover:bg-primary-subtlehighlights the row under the pointer, except selected rows. It needs the hover stylesheet, which@volvo-cars/css/styles_all-media.cssincludes.selected:bg-accent-blue-mediumhighlights rows witharia-selected="true".expanded:bg-accent-blue-mediumhighlights rows witharia-expanded="true".
Set data-nested="true" on a sub-row. Its first cell then has no top border, so the sub-row reads as part of its parent. See Nested rows.
| Model | Powertrain | In stock | On order |
|---|---|---|---|
| EX30 | Electric | 14 | 32 |
| XC60 | Plug-in hybrid | 9 | 21 |
| EX90 | Electric | 3 | 18 |
| XC40 | Mild hybrid | 11 | 6 |
Show code
<table class="table w-full font-14" aria-label="Cars in stock"> <thead> <tr> <th class="text-wrap">Model</th> <th class="text-wrap">Powertrain</th> <th class="text-wrap">In stock</th> <th class="text-wrap">On order</th> </tr> </thead> <tbody> <tr class="odd:bg-secondary hover:bg-primary-subtle selected:bg-accent-blue-medium" > <td>EX30</td> <td>Electric</td> <td>14</td> <td>32</td> </tr> <tr aria-selected="true" class="odd:bg-secondary hover:bg-primary-subtle selected:bg-accent-blue-medium" > <td>XC60</td> <td>Plug-in hybrid</td> <td>9</td> <td>21</td> </tr> <tr class="odd:bg-secondary hover:bg-primary-subtle selected:bg-accent-blue-medium" > <td>EX90</td> <td>Electric</td> <td>3</td> <td>18</td> </tr> <tr class="odd:bg-secondary hover:bg-primary-subtle selected:bg-accent-blue-medium" > <td>XC40</td> <td>Mild hybrid</td> <td>11</td> <td>6</td> </tr> </tbody></table>Sorting
Section titled “Sorting”Put the Sortable button inside TableHead and pass the column’s sort direction to isSorted. The arrow points up for ascending and down for descending, and stays hidden while the column is unsorted. Set aria-sort on the header cell.
Show code
import { type ColumnDef, createSortedRowModel, flexRender, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable,} from '@tanstack/react-table';import { Sortable, Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from '@volvo-cars/react-table';
type Car = { model: string; powertrain: string; inStock: number; onOrder: number;};
const features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel(), sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text },});
const data: Car[] = [ { model: 'EX30', powertrain: 'Electric', inStock: 14, onOrder: 32 }, { model: 'XC60', powertrain: 'Plug-in hybrid', inStock: 9, onOrder: 21 }, { model: 'EX90', powertrain: 'Electric', inStock: 3, onOrder: 18 }, { model: 'XC40', powertrain: 'Mild hybrid', inStock: 11, onOrder: 6 }, { model: 'V60', powertrain: 'Plug-in hybrid', inStock: 5, onOrder: 4 },];
const columns: ColumnDef<typeof features, Car>[] = [ { accessorKey: 'model', header: 'Model' }, { accessorKey: 'powertrain', header: 'Powertrain' }, { accessorKey: 'inStock', header: 'In stock' }, { accessorKey: 'onOrder', header: 'On order' },];
const ariaSort = { asc: 'ascending', desc: 'descending' } as const;
export function TableSorting() { const table = useTable({ features, columns, data });
return ( <Table aria-label="Cars in stock"> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { const sorted = header.column.getIsSorted(); const content = flexRender( header.column.columnDef.header, header.getContext(), ); return ( <TableHead key={header.id} colSpan={header.colSpan} aria-sort={sorted ? ariaSort[sorted] : undefined} > {header.column.getCanSort() ? ( <Sortable onClick={header.column.getToggleSortingHandler()} isSorted={sorted} > {content} </Sortable> ) : ( content )} </TableHead> ); })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows.map((row) => ( <TableRow key={row.id}> {row.getAllCells().map((cell) => ( <TableCell key={cell.id}> {flexRender(cell.column.columnDef.cell, cell.getContext())} </TableCell> ))} </TableRow> ))} </TableBody> </Table> );}TanStack Table sorts text columns A to Z first and number columns highest first. Set sortDescFirst on a column to change this.
Resizing columns
Section titled “Resizing columns”Register both columnSizingFeature and columnResizingFeature. Put a ResizeHandle in each TableHead whose column can resize (header.column.getCanResize()), and pass the header’s resize handler to its onMouseDown and onTouchStart. Set the widths on the Table, TableHead and TableCell. In right-to-left layouts, set columnResizeDirection: 'rtl' so the column edge follows the pointer. The handle shows when you hover over a header. On devices without hover, it’s always visible.
See Resizing columns.
Pagination
Section titled “Pagination”Pass the table to SimplePagination. It needs rowPaginationFeature and a paginatedRowModel, and reads table.state.pagination. pageSizeOptions defaults to [10, 20, 30]. Add Infinity to show an “All” option.
Show code
import { type ColumnDef, createPaginatedRowModel, flexRender, rowPaginationFeature, tableFeatures, useTable,} from '@tanstack/react-table';import { SimplePagination, Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from '@volvo-cars/react-table';
type Car = { model: string; powertrain: string; inStock: number; onOrder: number;};
const features = tableFeatures({ rowPaginationFeature, paginatedRowModel: createPaginatedRowModel(),});
const data: Car[] = [ { model: 'EX30', powertrain: 'Electric', inStock: 14, onOrder: 32 }, { model: 'XC60', powertrain: 'Plug-in hybrid', inStock: 9, onOrder: 21 }, { model: 'EX90', powertrain: 'Electric', inStock: 3, onOrder: 18 }, { model: 'XC40', powertrain: 'Mild hybrid', inStock: 11, onOrder: 6 }, { model: 'V60', powertrain: 'Plug-in hybrid', inStock: 5, onOrder: 4 },];
const columns: ColumnDef<typeof features, Car>[] = [ { accessorKey: 'model', header: 'Model' }, { accessorKey: 'powertrain', header: 'Powertrain' }, { accessorKey: 'inStock', header: 'In stock' }, { accessorKey: 'onOrder', header: 'On order' },];
export function TablePagination() { const table = useTable({ features, columns, data, initialState: { pagination: { pageIndex: 0, pageSize: 2 } }, });
return ( <div className="w-full"> <Table aria-label="Cars in stock"> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => ( <TableHead key={header.id} colSpan={header.colSpan}> {flexRender( header.column.columnDef.header, header.getContext(), )} </TableHead> ))} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows.map((row) => ( <TableRow key={row.id}> {row.getAllCells().map((cell) => ( <TableCell key={cell.id}> {flexRender(cell.column.columnDef.cell, cell.getContext())} </TableCell> ))} </TableRow> ))} </TableBody> </Table> <SimplePagination table={table} pageSizeOptions={[2, 4, Infinity]} /> </div> );}To translate the pagination, build it from its parts. See Localized pagination.
Action bar
Section titled “Action bar”The action bar holds actions for the selected rows. Show it when at least one row is selected, and hide it when none are.
TableActionBaris the bar. It opens at the bottom of the viewport.TableActionBarSelectionshows how many rows are selected.TableActionBarActionsholds up to three actions.TableActionBarDividerseparates actions.TableActionBarMenuandTableActionBarMenuOptionhold the actions beyond the first three.
useTableActionBar returns the props to spread on TableActionBar and TableActionBarMenu, and the functions to show and hide them. The menu opens above the bar with CSS anchor positioning. In browsers without anchor positioning, the hook positions it for you.
Show code
import { type ColumnDef, flexRender, rowSelectionFeature, tableFeatures, useTable,} from '@tanstack/react-table';import { IconButton } from '@volvo-cars/react-icons';import { Table, TableActionBar, TableActionBarActions, TableActionBarDivider, TableActionBarMenu, TableActionBarMenuOption, TableActionBarSelection, TableBody, TableCell, TableHead, TableHeader, TableRow, useTableActionBar,} from '@volvo-cars/react-table';import { useEffect } from 'react';
type Car = { model: string; powertrain: string; inStock: number; onOrder: number;};
const features = tableFeatures({ rowSelectionFeature });
const data: Car[] = [ { model: 'EX30', powertrain: 'Electric', inStock: 14, onOrder: 32 }, { model: 'XC60', powertrain: 'Plug-in hybrid', inStock: 9, onOrder: 21 }, { model: 'EX90', powertrain: 'Electric', inStock: 3, onOrder: 18 },];
const columns: ColumnDef<typeof features, Car>[] = [ { id: 'select', header: ({ table }) => ( <input type="checkbox" aria-label="Select all rows" checked={table.getIsAllRowsSelected()} ref={(input) => { if (input) { input.indeterminate = table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected(); } }} onChange={table.getToggleAllRowsSelectedHandler()} /> ), cell: ({ row }) => ( <input type="checkbox" aria-label={`Select ${row.original.model}`} checked={row.getIsSelected()} onChange={row.getToggleSelectedHandler()} /> ), }, { accessorKey: 'model', header: 'Model' }, { accessorKey: 'powertrain', header: 'Powertrain' }, { accessorKey: 'inStock', header: 'In stock' }, { accessorKey: 'onOrder', header: 'On order' },];
export function TableBulkEdit() { const table = useTable({ features, columns, data, enableRowSelection: true, }); const { actionBarProps, showActionBar, hideActionBar, actionBarMenuProps, showActionBarMenu, } = useTableActionBar();
const selectedCount = Object.keys(table.state.rowSelection).length;
useEffect(() => { if (selectedCount > 0) { showActionBar(); } else { hideActionBar(); } }, [selectedCount, showActionBar, hideActionBar]);
return ( // Leaves room below the table for the bar, which this preview pins to its bottom edge. <div style={{ minHeight: 400 }}> <Table aria-label="Cars in stock"> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => ( <TableHead key={header.id} colSpan={header.colSpan}> {flexRender( header.column.columnDef.header, header.getContext(), )} </TableHead> ))} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows.map((row) => ( <TableRow key={row.id} aria-selected={row.getIsSelected() ? true : undefined} className="odd:bg-secondary hover:bg-primary-subtle selected:bg-accent-blue-medium" > {row.getAllCells().map((cell) => ( <TableCell key={cell.id}> {flexRender(cell.column.columnDef.cell, cell.getContext())} </TableCell> ))} </TableRow> ))} </TableBody> </Table> <TableActionBar {...actionBarProps}> <IconButton bleed variant="clear" icon="x" aria-label="Clear selection" onClick={() => table.toggleAllRowsSelected(false)} /> <TableActionBarDivider /> <TableActionBarSelection> {selectedCount} {selectedCount === 1 ? 'car' : 'cars'} selected </TableActionBarSelection> <TableActionBarActions> <button className="button-text" type="button" data-arrow="none"> Reserve </button> <TableActionBarDivider /> <button className="button-text" type="button" data-arrow="none"> Transfer </button> <TableActionBarDivider /> <button className="button-text" type="button" data-arrow="none"> Export </button> <IconButton icon="three-dots" variant="clear" aria-label="More actions" onClick={showActionBarMenu} /> <TableActionBarMenu {...actionBarMenuProps}> <TableActionBarMenuOption> <button type="button">Mark as sold</button> </TableActionBarMenuOption> <TableActionBarMenuOption> <button type="button">Assign to retailer</button> </TableActionBarMenuOption> </TableActionBarMenu> </TableActionBarActions> </TableActionBar> </div> );}Accessibility
Section titled “Accessibility”- Name every table, with a
TableCaptionor anaria-label. - Use
TableHeadfor header cells. Give columns without a visible header, such as an actions column, a visually hidden label withsr-only. - Set
aria-sorton the header cell of the sorted column. - Give every checkbox a label that names its row, and label the select-all checkbox “Select all rows”. Set the select-all checkbox to
indeterminatewhen some, but not all, rows are selected. - Screen readers announce
aria-selectedon table rows inconsistently, so let the row’s checkbox carry the selected state. - Give icon buttons an
aria-label. Setaria-expandedon buttons that expand a row. - Resize handles only work with a pointer. Choose default column widths that show the content in full.
- Set
aria-busyon the table while it’s loading.
SimpleTable
Section titled “SimpleTable”| Prop | Type | Required | Default |
|---|---|---|---|
table | Table_Core<TFeatures, TData> | (Table_Core<TFea... | ✓ | - |
SimplePagination
Section titled “SimplePagination”| Prop | Type | Required | Default |
|---|---|---|---|
table | PaginationTable | ✓ | - |
pageSizeOptions | number[] | - | [10, 20, 30] |
Sortable
Section titled “Sortable”| Prop | Type | Required | Default |
|---|---|---|---|
isSorted | false | "asc" | "desc" | - | - |
PaginationPageSizeSelect
Section titled “PaginationPageSizeSelect”| Prop | Type | Required | Default |
|---|---|---|---|
options | number[] | ✓ | - |
PaginationPageSelect
Section titled “PaginationPageSelect”| Prop | Type | Required | Default |
|---|---|---|---|
totalPages | number | ✓ | - |
Migrating
Section titled “Migrating”- From
@volvo-cars/react-table0.3: react-table 0.3 → 0.4. - From
@volvo-cars/edls-css: Moving from edls-css to css.