Data Table
A table that sorts, selects and pages through data, on TanStack Table.
| Actions | ||||||
|---|---|---|---|---|---|---|
| PAY-001 | paid | ada@example.com | $250.00 | |||
| PAY-002 | pending | grace@example.com | $150.00 | |||
| PAY-003 | failed | alan@example.com | $350.00 | |||
| PAY-004 | paid | katherine@example.com | $450.00 | |||
| PAY-005 | paid | linus@example.com | $550.00 |
Page 1 of 2
Installation
npx shadcn@latest add @oakoss/data-tableUsage
import {
DataTable,
DataTableContent,
DataTableToolbar,
} from '#/components/ui/data/data-table';
import { DataTableActionBar } from '#/components/ui/data/data-table-action-bar';
import {
currencyColumn,
selectionColumn,
} from '#/components/ui/data/data-table-columns';
import { DataTablePagination } from '#/components/ui/data/data-table-pagination';
import { DataTableViewOptions } from '#/components/ui/data/data-table-view-options';
import { type DataTableColumn, useDataTable } from '#/hooks/use-data-table';
const columns: DataTableColumn<Payment>[] = [
selectionColumn<Payment>(),
{ accessorKey: 'id', header: 'Payment', meta: { isRowHeader: true } },
currencyColumn<Payment>('amount', { currency: 'USD', header: 'Amount' }),
];
function Payments({ payments }: { payments: Payment[] }) {
const table = useDataTable({
columns,
data: payments,
enableRowSelection: true,
getRowId: (payment) => payment.id,
});
return (
<DataTable table={table}>
<DataTableToolbar>
<DataTableViewOptions />
</DataTableToolbar>
<DataTableContent aria-label="Payments" />
<DataTableActionBar />
<DataTablePagination />
</DataTable>
);
}useDataTable creates a TanStack Table with
sorting, filtering, pagination, selection and column visibility registered,
and DataTable hands it to every part inside, so the parts compose in any
layout. Keep columns outside the component, or memoize them: a new array
each render rebuilds the rows.
Each state slice (sorting, pagination, selection, columnVisibility,
columnFilters and globalFilter) is the hook's own until you pass it in
state, and its change handler (onSortingChange and so on) hears every
change either way. That's how a slice moves into the URL or a store. Set
starting values with defaultState.
Column meta tells the parts what a header can't: label names the column
in the column menu and announcements when its header isn't text, align
and className style its cells, and isRowHeader makes its cells head their
rows. To add your own keys, edit DataTableColumnMeta in the installed hook.
Examples
Server data
With mode: 'server', the table shows data as given and pages through
rowCount rows, and the type asks for that count. Sorting or filtering
returns to the first page. dataTableQuery turns the state into a 1-based
page, pageSize, a sort like -total and the filters, for a URL or a
fetch; put the same values in your data library's cache key. The table
doesn't fetch, so any data library fits.
| ORD-001 | $15.00 |
|---|---|
| ORD-002 | $385.00 |
| ORD-003 | $755.00 |
| ORD-004 | $225.00 |
| ORD-005 | $595.00 |
Page 1 of 9
Query: page=1&pageSize=5
Loading, refetching, empty and errors
isLoading shows skeleton rows for the first load, with a visually hidden
loadingLabel for screen readers. isRefetching keeps the rows on screen,
faded, while new ones load, such as with TanStack Query's
placeholderData: keepPreviousData. An error shows as an alert, which
can hold a retry button: above the rows when a refetch fails, so they stay
readable, or in place of them when the first load fails. The alert stays
through a retry, so focus on a retry button inside it stays put; when an
isRefetching retry ends with the error still set, the table announces
retryFailedLabel ("Retry failed"). Rows kept under
an error should be the current page's: data held over from another page or
order would sit under a pager and headers that no longer describe it. With
no rows the body says emptyLabel, or noResultsLabel while a filter is set.
<DataTableContent
aria-label="Payments"
error={query.isError && 'Payments failed to load.'}
isLoading={query.isPending}
isRefetching={query.isPlaceholderData}
/>Column presets
selectionColumn adds row checkboxes and a box for the page. numberColumn,
currencyColumn and dateColumn format values for the app's locale and align
numbers to the end. actionsColumn takes a cell per row, under a header
named for screen readers only. linkColumn puts a link in each row's heading
cell that covers the whole row, so a click anywhere opens it while the
checkbox and actions keep their own clicks; it suits a table whose first
column isn't sticky.
Filters
Filters ship as their own item, which adds a search, faceted filters and the active filters:
npx shadcn@latest add @oakoss/data-table-filtersDataTableSearch filters the whole table, or one column with column, once
typing pauses (150ms, or 300ms when the server filters), and shows a change
the app makes to the search, such as from the URL. It matches the raw values,
not their formatting, so "$100" doesn't find an amount of 100.
DataTableFacetedFilter picks values from a column's meta.options, which it
requires; build them from the data when the values aren't known ahead. An
option's value is the cell's value as text, and a date's is its ISO string. Each
option shows a count that follows the other filters, and a column with options
keeps rows whose value equals a picked one. A column that names its own
filterFn receives the picked values as an array of strings. A server table
passes counts from its API, keyed by option value, since a page of rows
can't count the whole result. DataTableFilterChips shows one chip per
filtered column and a Reset button. A column takes one kind of filter: a
search or a facet, not both.
| ORD-001 | Ada Lovelace | shipped | $120.00 |
|---|---|---|---|
| ORD-002 | Grace Hopper | processing | $80.00 |
| ORD-003 | Alan Turing | cancelled | $45.00 |
| ORD-004 | Katherine Johnson | shipped | $210.00 |
| ORD-005 | Linus Torvalds | processing | $60.00 |
Page 1 of 2
Selection and bulk actions
DataTableActionBar appears while rows are selected, with the count, Clear,
and the actions you pass as children. It sits after the table and sticks to
the bottom of the screen, so ticking the first row moves only what follows.
Once a page's rows are all ticked and more rows match, it offers to select
every matching row; a server table counts those from rowCount. A new filter
or search ends that selection, while sorting and paging keep it. A client
table notes selected rows a filter hides; a server table can't tell those
from rows on another page.
The selection slice is { ids }, or { all, except } for every row
matching all, the filters and search it was made under, apart from the
except ids. A server action receives the selection and applies all when
it runs, so it acts on the rows matching then; its own rules decide which
rows it may change, as enableRowSelection does on the page. A client action
reads the rows with selectedRows(table). Confirm a destructive action with
the count in an Alert Dialog, which focuses
Cancel, and keep the rows that failed selected:
| INV-001 | sent | |
|---|---|---|
| INV-002 | draft | |
| INV-003 | draft | |
| INV-004 | draft | |
| INV-005 | sent |
Page 1 of 3
Linking to a row
linkedRowId marks the row a link points to, such as ?payment=PAY-014 in
the URL. On client data it brings up that row's page, scrolls the row into
view and focuses its row header, once per link, so paging away afterwards
stays put. With server data, fetch the page holding the row yourself.
Accessibility
DataTable renders Table's native table elements,
following the
WAI-ARIA table pattern, with
each control inside a tab stop of its own. Name the table with aria-label
or aria-labelledby on DataTableContent.
A sortable column's header holds a button: each press sorts ascending,
descending, then unsorted, and Shift adds the column to the order instead of
replacing it. The first sort column's header carries aria-sort, which ARIA
allows on one header at a time; later ones show their place in the order.
Selected rows carry aria-selected and their checkbox is checked. Shift with
a click or Space selects the range from the last row pressed. The header box
selects the page's rows, and reads mixed while only some are selected. The
action bar is a toolbar
named "Selected rows", after the table in the reading order; Escape inside
it clears the selection. When it goes, focus left in it moves to the header
box, or with no rows left, to the table's first control. Controls in the table keep a bottom scroll margin, so focus scrolled
into view stays clear of the bar.
While a page holds part of the result, the table carries aria-rowcount and
each row aria-rowindex, so screen readers say where a row sits in the
whole. Sorting, paging, filtering and selecting change the table without
moving focus, so a polite live region says what changed, such as "Sorted by
Amount, ascending". The table is busy (aria-busy) while loading or
refetching.
A faceted filter is a Select with multiple
selection, so its list follows the
WAI-ARIA listbox pattern:
each option is named by its label and reads its count as its description,
and the trigger's name includes how many values are chosen. Past seven
options a search field leads the list and takes focus as it opens. The
active filters are a Tag Group, whose tags
remove with Delete or Backspace. Clearing every filter, from Reset or the
no-results state, moves focus to the search field.
| Key | Action |
|---|---|
Tab | Moves to the next control in the table |
Enter or Space | On a header button, steps the sort |
Shift + Enter | On a header button, adds the column to the sort |
Space | On a row checkbox, selects or clears the row |
Shift + Space | On a row checkbox, selects the range from the last |
Arrow Up / Down | In a faceted filter's list, moves between options |
Enter or Space | In a faceted filter's list, chooses or clears one |
Delete / Backspace | On an active filter, removes it |
Arrow Left / Right | In the action bar, moves between its controls |
Escape | In the action bar, clears the selection |
Every string is a prop with an English default: the labels on
DataTableContent, DataTableActionBar, DataTablePagination,
DataTableViewOptions and the column presets, and the announcements through
DataTable's messages.
API
DataTable
A div that holds the table for the parts inside it and its live region.
Props
Prop
Type
Also accepts div props.
DataTableContent
Table with the table's header and rows.
Props
Prop
Type
Also accepts Table's props.
DataTableActionBar
A React Aria Toolbar with the
selected count, Clear and your actions; it renders nothing while nothing is
selected. children can be a function of the selection and its counts.
Props
Prop
Type
Also accepts React Aria Toolbar's props.
DataTablePagination
A page size select, the page and step buttons.
Props
Prop
Type
Also accepts div props.
DataTableViewOptions
A Dropdown Menu that shows and hides the data columns that can hide.
Props
Prop
Type
DataTableToolbar
A div that lays out controls above the table, such as filters and the
column menu, accepting div props.
DataTableSearch
A Search Field that filters the table, from
the data-table-filters item.
Props
Prop
Type
Also accepts Search Field's props, except its value.
DataTableFacetedFilter
A multiple-selection Select that filters a column
to the values chosen, from the data-table-filters item.
Props
Prop
Type
DataTableFilterChips
A Tag Group of the active filters and a Reset
button, from the data-table-filters item; it renders nothing while nothing
is filtered.
Props
Prop
Type
Also accepts div props.
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: data-table, data-table-toolbar, data-table-head, data-table-sort, data-table-body, data-table-row, data-table-action-bar, data-table-action-bar-clear, data-table-pagination, data-table-view-options, data-table-announcer, data-table-faceted-filter or data-table-filter-chips; data-table-error on the alert row above kept rows; data-table-retry on the visually hidden region that announces a failed retry |