# Data table

A Table with a toolbar: search, filters, a column picker, bulk actions, paging or virtualization, and its view kept in the URL.

- Family: collection
- Import: `import { DataTable } from "@senvenli/react/collection";`
- Page: https://design.senvenli.com/docs/components/data-table
- JSON: https://design.senvenli.com/docs/components/data-table.json

## Example: Orders

A client list of forty rows: search, a status filter, a column picker, paging and a bulk action.

```tsx
import { useState } from "react";
import { CalendarDate } from "@internationalized/date";
import { DataTable, useDataTableUrl, type DataTableColumn } from "@senvenli/react/collection";
import { Badge } from "@senvenli/react/display";

const STATUS = {
  paid: { label: "Paid", tone: "success" },
  pending: { label: "Pending", tone: "warning" },
  shipped: { label: "Shipped", tone: "information" },
  refunded: { label: "Refunded", tone: "neutral" },
} as const;
type Status = keyof typeof STATUS;
type Order = { id: string; customer: string; date: string; status: Status; total: number };

// Forty fixed orders: index arithmetic, never a random value or today's date.
const CUSTOMERS = ["Ada Lovelace", "Grace Hopper", "Alan Turing", "Katherine Johnson", "Margaret Hamilton", "Barbara Liskov", "Donald Knuth"];
const STATUSES: Status[] = ["paid", "pending", "paid", "shipped", "paid", "refunded"];
const FIRST_DAY = new CalendarDate(2026, 2, 7);
const ORDERS: Order[] = Array.from({ length: 40 }, (_, index) => ({
  id: `SO-${1042 + index}`,
  customer: CUSTOMERS[index % CUSTOMERS.length]!,
  date: FIRST_DAY.add({ days: index }).toString(),
  status: STATUSES[index % STATUSES.length]!,
  total: 45 + ((index * 37) % 23) * 18.5,
}));

const usd = new Intl.NumberFormat("en", { style: "currency", currency: "USD" });
const day = new Intl.DateTimeFormat("en", { month: "short", day: "numeric", timeZone: "UTC" });
const COLUMNS: DataTableColumn<Order>[] = [
  { key: "id", header: "Order", isRowHeader: true, isSortable: true },
  { key: "customer", header: "Customer", isSortable: true },
  // Sorted and searched by the ISO date under `key`, shown short.
  { key: "date", header: "Date", isSortable: true, isHideable: true, render: (order) => day.format(new Date(order.date)) },
  { key: "status", header: "Status", isHideable: true, render: (order) => <Badge tone={STATUS[order.status].tone}>{STATUS[order.status].label}</Badge> },
  { key: "total", header: "Total", align: "end", isSortable: true, render: (order) => usd.format(order.total) },
];
const FILTERS = [{ key: "status", label: "Status", options: Object.entries(STATUS).map(([id, status]) => ({ id, label: status.label })) }];

const SORT = { column: "date", direction: "descending" } as const;

export default function Example() {
  const [orders, setOrders] = useState(ORDERS);
  // The view lives in the URL (?orders.page=2&orders.status=paid); the prefix keeps two tables on a page apart.
  const url = useDataTableUrl({ filters: FILTERS, defaultSort: SORT, urlKey: "orders" });
  return (
    <DataTable
      {...url}
      aria-label="Orders"
      rows={orders}
      columns={COLUMNS}
      filters={FILTERS}
      defaultSort={SORT}
      pageSize={10}
      bulkActions={[
        {
          id: "ship",
          label: "Mark as shipped",
          // Gets the selected ids from every page; the selection clears once this returns.
          onAction: (keys) => setOrders((current) => current.map((order) => (keys.includes(order.id) ? { ...order, status: "shipped" } : order))),
        },
      ]}
    />
  );
}
```

## Examples

### A server list

`query` fetches one page for the current view; the table shows loading, empty and error states itself.

```tsx
import { DataTable, useDataTableUrl, type DataTableQuery, type DataTableResult } from "@senvenli/react/collection";
import { EmptyState } from "@senvenli/react/feedback";

type Customer = { id: string; name: string; city: string; orders: number };

const NAMES = ["Ada Lovelace", "Grace Hopper", "Alan Turing", "Katherine Johnson", "Margaret Hamilton", "Barbara Liskov", "Donald Knuth", "Edsger Dijkstra"];
const CITIES = ["Boston", "Chicago", "Denver", "Portland", "Austin"];
const CUSTOMERS: Customer[] = Array.from({ length: 23 }, (_, index) => ({
  id: `C-${200 + index}`,
  name: NAMES[index % NAMES.length]!,
  city: CITIES[index % CITIES.length]!,
  orders: 3 + ((index * 11) % 17),
}));

// Stands in for your API: it gets the page, the page size, the search, the sort and the filters.
async function fetchCustomers({ page, pageSize, search }: DataTableQuery): Promise<DataTableResult<Customer>> {
  await new Promise((resolve) => setTimeout(resolve, 400));
  const found = CUSTOMERS.filter((customer) => customer.name.toLowerCase().includes(search.trim().toLowerCase()));
  return { rows: found.slice((page - 1) * pageSize, page * pageSize), total: found.length };
}

export default function Example() {
  const url = useDataTableUrl({ urlKey: "customers" });
  return (
    <DataTable
      {...url}
      aria-label="Customers"
      query={fetchCustomers}
      pageSize={5}
      columns={[
        { key: "name", header: "Customer" },
        { key: "city", header: "City" },
        { key: "orders", header: "Orders", align: "end" },
      ]}
      emptyState={<EmptyState size="small" icon="inbox" title="No customers yet" description="Customers appear here after their first order." />}
    />
  );
}
```

## Guidelines

### When to use it

- A record list people search, filter and act on in bulk: orders, customers, invoices.

### Use something else when

- [table](https://design.senvenli.com/docs/components/table.md): A short, fixed list with no tools.

## Accessibility

Keyboard:

- Arrow keys: Move between cells and rows.
- Tab: Moves between the toolbar, the table and the pager.

Built in:

- Loading, empty, no-results and failed states have their own copy.
- The selected count is announced in the bulk bar.

You provide:

- An aria-label, and labels for filters and bulk actions.

## API reference

### DataTable

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| aria-label | `string` |  | yes | Names the table ("Orders"). |
| columns | `readonly DataTableColumn<T>[]` |  | yes |  |
| rowKey | `(row: T) => Key` |  | no | The row's stable id; `row.id` by default. Selection is kept by it across pages. Ids must be unique within the list; build one from the fields that are when the data has none (`${row.date}:${row.channel}`). A repeated id on a page still renders every row: the later ones are keyed `a#2`, `a#3`, … in row order, and selection, bulk actions and `onRowAction` receive those suffixed keys; a development warning names the repeated ids. A suffixed key follows the row's position, not the row: after a sort, filter or page change a selection made through it can move to another copy, and an id repeated on two pages is one key, so selecting it on one page selects it on both. |
| filters | `readonly DataTableFilter[]` |  | no |  |
| bulkActions | `readonly DataTableBulkAction[]` |  | no |  |
| defaultSort | `SortDescriptor` |  | no |  |
| columnVisibility | `Readonly<Record<string, boolean>>` |  | no | Column key → shown; columns left out are shown. Pass with `onColumnVisibilityChange` to own it. |
| onColumnVisibilityChange | `(visibility: Record<string, boolean>) => void` |  | no |  |
| onRowAction | `(key: Key) => void` |  | no | Opens the record (row press while nothing is selected). |
| pageSize | `number` |  | no | 20 by default. |
| formatRange | `(from: number, to: number, total: number) => string` |  | no | The range sentence: (41, 60, 1204) → "41–60 of 1,204". |
| emptyState | `React.ReactNode` |  | no | What an empty list shows (with no search or filter active): an `EmptyState size="small"` with the action that fills it. "No records yet" by default. |
| view | `DataTableView` |  | no | The view (page, sort, search, filters), controlled. Keep it in the URL with `useDataTableUrl`, or anywhere else; left out, the table keeps it itself. |
| defaultView | `Partial<DataTableView>` |  | no | The first view when uncontrolled: page 1, the default sort, no search and no filters by default. |
| onViewChange | `(view: DataTableView) => void` |  | no | Called with the whole next view on every change (a new sort, search, filter or page). |
| density | `Density` |  | no | `compact` (36px rows) by default: DataTable is the dense working list of a back office. |
| query | `(view: DataTableQuery, signal: AbortSignal) => Promise<DataTableResult<T>>` |  | no | A server list: fetches one page for the view; aborted when the view changes again. It is read when the view changes, not when the function does: for a list that depends on something else (a parent tab), give the DataTable a `key` from it so it starts afresh. |
| rows | `readonly T[]` |  | no | A client list: searched, filtered and sorted here; paged, or virtualized when long. |
| virtualizeAbove | `number` |  | no | Client lists longer than this render only the rows in view instead of pages. 200 by default. |
| height | `number` |  | no | The virtualized list's height in px. 480 by default. |

### Tokens it reads

`--ds-background-selected`, `--ds-border`, `--ds-border-focused`, `--ds-border-selected`, `--ds-radius-large`, `--ds-radius-medium`, `--ds-shadow-overflow`, `--ds-shadow-overlay`, `--ds-shadow-raised`, `--ds-size-row`, `--ds-size-row-compact`, `--ds-space-050`, `--ds-space-150`, `--ds-space-200`, `--ds-space-300`, `--ds-space-400`, `--ds-space-500`, `--ds-surface-hovered`, `--ds-surface-overlay`, `--ds-surface-raised`, `--ds-surface-sunken`, `--ds-text`, `--ds-text-subtle`, `--ds-text-subtlest`

## Related

- [table](https://design.senvenli.com/docs/components/table.md)
- [pagination](https://design.senvenli.com/docs/components/pagination.md)
- [toolbar](https://design.senvenli.com/docs/components/toolbar.md)
