Skip to content

Table

Edit on GitHub

Show structured data in rows and columns, with optional sorting, row selection, pagination and bulk actions.

@volvo-cars/css v3.3.1@volvo-cars/react-table v0.4.0

@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.

ModelPowertrainIn stockOn order
EX30Electric1432
XC60Plug-in hybrid921
EX90Electric318
Show codeHide 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>
);
}

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.

@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.

Terminal window
yarn add @volvo-cars/react-table @tanstack/react-table

Install @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.

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.

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.

ModelPowertrainIn stockOn order
EX30Electric1432
XC60Plug-in hybrid921
EX90Electric318
Show codeHide 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.

Model Powertrain In stock On order
EX30 Electric 14 32
XC60 Plug-in hybrid 9 21
EX90 Electric 3 18
Show codeHide 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>

Add these classes to rows:

  • odd:bg-secondary stripes every other row.
  • hover:bg-primary-subtle highlights the row under the pointer, except selected rows. It needs the hover stylesheet, which @volvo-cars/css/styles_all-media.css includes.
  • selected:bg-accent-blue-medium highlights rows with aria-selected="true".
  • expanded:bg-accent-blue-medium highlights rows with aria-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 codeHide 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>

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.

EX30Electric1432
XC60Plug-in hybrid921
EX90Electric318
XC40Mild hybrid116
V60Plug-in hybrid54
Show codeHide 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.

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.

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.

ModelPowertrainIn stockOn order
EX30Electric1432
XC60Plug-in hybrid921
Show codeHide 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.

The action bar holds actions for the selected rows. Show it when at least one row is selected, and hide it when none are.

  • TableActionBar is the bar. It opens at the bottom of the viewport.
  • TableActionBarSelection shows how many rows are selected.
  • TableActionBarActions holds up to three actions.
  • TableActionBarDivider separates actions.
  • TableActionBarMenu and TableActionBarMenuOption hold 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.

volvocars.com
Show codeHide 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>
);
}
  • Name every table, with a TableCaption or an aria-label.
  • Use TableHead for header cells. Give columns without a visible header, such as an actions column, a visually hidden label with sr-only.
  • Set aria-sort on 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 indeterminate when some, but not all, rows are selected.
  • Screen readers announce aria-selected on table rows inconsistently, so let the row’s checkbox carry the selected state.
  • Give icon buttons an aria-label. Set aria-expanded on buttons that expand a row.
  • Resize handles only work with a pointer. Choose default column widths that show the content in full.
  • Set aria-busy on the table while it’s loading.
PropTypeRequiredDefault
tableTable_Core<TFeatures, TData> | (Table_Core<TFea...✓-
PropTypeRequiredDefault
tablePaginationTable✓-
pageSizeOptionsnumber[]-[10, 20, 30]
PropTypeRequiredDefault
isSortedfalse | "asc" | "desc"--
PropTypeRequiredDefault
optionsnumber[]✓-
PropTypeRequiredDefault
totalPagesnumber✓-