Data Table

Rows to sort, search, filter, select and page.

Source
$npx @dinachi/cli@latest add data-table
Actions
Ada OkaforPendingAndroid217 Nov, 15:42£204.00
Lukas BergPendingWeb117 Nov, 12:55£68.95
Tomás HerreraPendingiOS117 Nov, 09:07£118.00
Leila HaddadPaidAndroid317 Nov, 06:21£155.00
Mei LinPaidWeb317 Nov, 03:13£220.00
Hana NovakPaidAndroid317 Nov, 00:34£242.00
Hana NovakPaidiOS216 Nov, 21:01£86.00
Ada OkaforPaidAndroid216 Nov, 19:18£182.95
Ada OkaforPaidiOS316 Nov, 16:02£220.95
Felix WagnerPaidIn store316 Nov, 12:15£116.95
1–10 of 248Rows
density
state
expandable
selectable
disabled

Usage

import { DataTable, createColumnHelper } from "@/components/ui/data-table"

type Order = { id: number; customer: string; status: string; amount: number }
const col = createColumnHelper<Order>()

const columns = [
  col.accessor("id", { header: "Order", size: 84, meta: { pin: "left", phone: "meta" } }),
  col.accessor("customer", { header: "Customer", meta: { phone: "title" } }),
  col.accessor("status", { header: "Status", size: 100, meta: { phone: "meta" } }),
  col.accessor("amount", { header: "Amount", size: 96, meta: { numeric: true, phone: "value" } }),
]

export function Orders({ orders }: { orders: Order[] }) {
  return (
    <DataTable
      data={orders}
      columns={columns}
      noun={{ singular: "order", plural: "orders" }}
      facet={{ column: "status" }}
    />
  )
}

Examples

248 orders

Actions
Ada OkaforPendingAndroid217 Nov, 15:42£204.00
Lukas BergPendingWeb117 Nov, 12:55£68.95
Tomás HerreraPendingiOS117 Nov, 09:07£118.00
Leila HaddadPaidAndroid317 Nov, 06:21£155.00
Mei LinPaidWeb317 Nov, 03:13£220.00
Hana NovakPaidAndroid317 Nov, 00:34£242.00
Hana NovakPaidiOS216 Nov, 21:01£86.00
Ada OkaforPaidAndroid216 Nov, 19:18£182.95
Ada OkaforPaidiOS316 Nov, 16:02£220.95
Felix WagnerPaidIn store316 Nov, 12:15£116.95
1–10 of 248Rows
Search, status chips with counts, sorting, selection, row menus and paging, all on the client.
import { DataTable, DataTableAction, DataTableRowTrigger, createColumnHelper } from '@/components/ui/data-table';

type Order = { id: number; customer: string; status: string; placed: Date; amount: number };
const col = createColumnHelper<Order>();

const columns = [
  col.accessor('id', {
    header: 'Order',
    size: 84,
    enableHiding: false,
    meta: { pin: 'left', phone: 'meta' },
    cell: (c) => <DataTableRowTrigger>#{c.getValue()}</DataTableRowTrigger>,
  }),
  col.accessor('customer', { header: 'Customer', meta: { phone: 'title' } }),
  col.accessor('status', { header: 'Status', size: 100, meta: { phone: 'meta', phoneOrder: 2 } }),
  col.accessor('placed', {
    header: 'Placed',
    sortingFn: 'datetime',
    // The phone line has room for the day, not the time.
    meta: { phone: 'meta', phoneOrder: 1, phoneCell: (c) => c.getValue().toLocaleDateString() },
    cell: (c) => c.getValue().toLocaleString(),
  }),
  col.accessor('amount', { header: 'Amount', size: 96, meta: { numeric: true, phone: 'value' } }),
];

export function Example({ orders }: { orders: Order[] }) {
  return (
    <DataTable
      data={orders}
      columns={columns}
      getRowLabel={(o) => `Order #${o.id}`}
      noun={{ singular: 'order', plural: 'orders' }}
      facet={{ column: 'status' }}
      rowActions={() => (
        <>
          <DataTableAction>Copy order ID</DataTableAction>
          <DataTableAction destructive>Refund</DataTableAction>
        </>
      )}
    />
  );
}

Notes

Server mode

Set rowCount and the table stops sorting, filtering and paging on its own. Control the state, fetch on each change and pass the page back as data. onStateChange hands you every slice at once:

<DataTable
  data={page.rows}
  rowCount={page.total}
  loading={pending}
  sorting={state.sorting}
  pagination={state.pagination}
  globalFilter={state.globalFilter}
  columnFilters={state.columnFilters}
  onStateChange={setState}
/>

The state holds selection and column visibility too, so refetch only when sorting, filters, search or paging changed; the Server-side example compares them.

With a page at a time, the header checkbox selects the page and the bar offers Select all 248. That selects every row on the server: each page arrives selected, and selectionActions gets selection.all, so act on the query rather than the ids. A new search or filter, Clear, or unticking a row ends it.

Selection and filters

Selected rows stay selected when a filter hides them. The bar counts the ones in view and says how many are hidden, and selectionActions gets only the ones in view, so a bulk action never reaches a row nobody can see. Clear drops both.

Phone

Below 768px the table becomes a list with no sideways scroll. Each row is two lines from the phone meta: the title and value columns, then the meta ones, ordered by phoneOrder. phoneCell renders a column there more briefly, such as a date without its time. Filters scroll as a chip row, one control by the title sorts, and tapping a row opens it in a sheet listing every visible column, with the row actions in its header.

Select, by the title, turns the rows into checkboxes and the search into the selection bar; a long press does the same and selects that row. Done clears the selection.

Changes and details

Every handler gets (value, details). details.cancel() refuses the change, and isAgentChange(details) tells you an agent made it. A sort, filter or search also sends the page back to 1, as a second change with its own details.

Pinned columns

The checkbox, the expander and any pin: "left" column stay put as the rest scrolls, with a shadow only while something is under them. Give pinned columns a size.

API

dataT[]
The rows. In server mode, only the page on show.
columnsColumnDef<T>[]
TanStack column definitions. Build them with createColumnHelper. Extras go on meta, below.
getRowId(row, index) => string = row.id
A stable id per row, so selection survives sorting and paging.
getRowLabel
agent
(row, id) => string = "Order 4821"
What a row is called in checkbox names, the sheet title and the agent.
noun
agent
{ singular, plural } = { "row", "rows" }
What the rows are. Names the count, the empty states and the agent's controls.
titleReactNode | null = "248 orders"
The heading over the table. null hides it.
facet
agent
{ column, options? }
A column whose values become filter chips, with counts. Pass options with a count each in server mode.
sorting, defaultSorting, onSortingChange
agent
SortingState
Controlled or starting sort. Shift-click adds a column.
columnFilters, defaultColumnFilters, onColumnFiltersChange
agent
ColumnFiltersState
The facet filter and any of your own.
globalFilter, defaultGlobalFilter, onGlobalFilterChange
agent
string
The search.
pagination, defaultPagination, onPaginationChange
agent
{ pageIndex, pageSize }
The page, from 0, and its size.
rowSelection, defaultRowSelection, onRowSelectionChange
agent
Record<id, boolean>
Selected rows by id.
columnVisibility, defaultColumnVisibility, onColumnVisibilityChangeRecord<id, boolean>
Columns hidden from the Columns menu.
columnOrder, defaultColumnOrder, onColumnOrderChangestring[]
The movable columns left to right, by id. Save it to keep someone's layout.
columnSizing, defaultColumnSizing, onColumnSizingChangeRecord<id, number>
Widths in px of the columns someone resized.
onStateChange(state, details) => void
Runs after any slice changes, with all of them. One handler for server mode.
rowCountnumber
The total on the server. Setting it turns off client sorting, filtering and paging.
pageSizesnumber[] = [10, 25, 50]
Choices in the Rows select. One entry hides it.
loadingboolean = false
Skeleton rows under the real header.
errorboolean | ReactNode
true reads Couldn't load orders. A node replaces the message.
onRetry() => void
Adds Try again to the error.
emptyState(context) => ReactNode
Replaces the empty message. Gets the query, the facet value and clear().
density"comfortable" | "compact" = "comfortable"
48px or 36px rows.
selectable
agent
boolean = true
The checkbox column and the selection bar.
selectionActions(rows, clear, selection) => ReactNode
Buttons in the selection bar. rows are the selected rows the filters show; selection has their ids, the hidden ones, the count, and all once every row on the server is chosen.
onRowOpen(row, details) => void
Opens a row on click, Enter or its row trigger, instead of the sheet. Rows get a pointer.
searchDelaynumber
Waits this many ms after the last keystroke before searching. Use it in server mode.
toolbarReactNode
More controls after the filter chips, such as a second filter.
onFilteredRowsChange(rows) => void
The rows left after search and filters, before paging. Client mode only.
rowActions(row) => ReactNode
Items for each row's menu, usually DataTableActions.
getSubRows(row) => T[] | undefined
Child rows, shown under a chevron.
renderSubComponent(row) => ReactNode
A panel under an expanded row. Not drawn while virtualized, where every row has a fixed height; use getSubRows there.
resizableboolean = true
Drag a header's edge, or focus it and press the arrows.
reorderableboolean = true
Drag a header, or use Move columns in the Columns menu.
virtualizeboolean = false
Draws only the rows in view, in a scrolling body, instead of pages.
maxHeightnumber
Height of the scrolling area in px. 452 when virtualized.
disabled
agent
boolean = false
Blocks people and agents.

Agent

Inside an AgentProvider, it appears in agent.snapshot() as select.

Reads

Sort orders

A multiple select. Its value is the sort in order, such as Amount descending; its items, each column both ways.

Select orders

A checkbox-group of the rows on the page, by their getRowLabel. Its value is every selected row. On phone too.

Search orders

The search input.

Filter orders by Status

The facet's toggle-group.

Pages of orders

The page, a number.

Rows per page

The page size, a select.

Actions

select("Amount descending")

Sorts by a column. A bare column name takes its natural first direction; sortLabels such as Newest work too.

setValue(["Status ascending", "Amount descending"])

Sorts by several columns.

clear()

Back to the default sort, on Sort; no rows selected, on Select.

select("Order #4821")

Selects rows by label or id, on Select. "all" selects everything that matches.

An agent's change runs through the same handlers as a person's, with isAgentChange(details) true; details.cancel() refuses it. A column that cannot sort, or a row that is not there, is refused with what is.

await agent.act({
  steps: [
    { ref: "Filter orders by Status", action: "select", args: ["Paid"] },
    { ref: "Sort orders", action: "select", args: ["Amount descending"] },
    { ref: "Select orders", action: "select", args: ["Order #4821"] },
  ],
})

Accessibility

  • An ARIA grid named by its title, with aria-rowcount for every row, not just the page, and aria-rowindex on each.
  • Sorted headers carry aria-sort, and a polite live region reads the new sort and count. It stays quiet while there is an error, which is an alert.
  • Paging keeps focus on the page button while the next page loads, and Try again keeps it in the grid.
  • Checkboxes are named Select page, or Select all when virtualized, and Select Order #4821; selected rows have aria-selected.
  • Resize handles are separators named Resize Amount, with their width as aria-valuenow. Headers are named by their label alone.
  • Column order changes from the Columns menu as well as by drag.
  • Phone rows are buttons, at least 44px tall, and paging uses 44px targets. In Select mode each row is a checkbox.
  • Long press is a shortcut only; the Select button reaches the same mode by tap, keyboard or screen reader.