# Data Table

Sortable, filterable, selectable, expandable, and paginated tables powered by TanStack Table.

Data Table combines TanStack Table state with Zenos table markup, pagination, loading states, and accessible controls. Use it for structured datasets that need interaction beyond a static Table.

<p className="zenos-recipe-source">
  Powered by <a href="https://tanstack.com/table/latest">TanStack Table</a> for sorting, filtering,
  pagination, selection, expansion, and column state. Zenos owns the rendered table, controls,
  loading and empty states, and keyboard integration.
</p>

## Installation

```bash
pnpm dlx @zentara-co/zenos-cli add data-table
npx @zentara-co/zenos-cli add data-table
yarn dlx @zentara-co/zenos-cli add data-table
bunx @zentara-co/zenos-cli add data-table
```

The command installs `@tanstack/react-table` and `@phosphor-icons/react`, then adds `data-table.tsx` to the consumer project. Import the recipe through the path configured by your application:

```tsx
import { DataTable, type DataTableColumnDef } from "./components/data-table";
```

Data tables are application-specific. Keep domain columns, filters, and row actions near the feature that owns the data. Extract a shared wrapper only after multiple tables need the same behavior.

## Basic table

Define the row shape first, then describe each visible column. Accessor columns are sortable by default; set `enableSorting: false` for columns such as selection or actions.

```tsx
import { Badge } from "@zentara-co/zenos-ui";
import { DataTable, type DataTableColumnDef } from "@docs/src/recipes/datatable/data-table";

type Asset = {
  id: string;
  name: string;
  owner: string;
  risk: number;
  severity: "Critical" | "High" | "Medium" | "Low";
  summary: string;
};

const assets: Asset[] = [
  {
    id: "asset-1",
    name: "Production API",
    owner: "Platform",
    risk: 96,
    severity: "Critical",
    summary: "Public API with two overdue critical findings.",
  },
  {
    id: "asset-2",
    name: "Customer portal",
    owner: "Web",
    risk: 82,
    severity: "High",
    summary: "Customer-facing application awaiting dependency upgrades.",
  },
  {
    id: "asset-3",
    name: "Analytics worker",
    owner: "Data",
    risk: 58,
    severity: "Medium",
    summary: "Background processor isolated from public traffic.",
  },
  {
    id: "asset-4",
    name: "Documentation",
    owner: "Developer Experience",
    risk: 18,
    severity: "Low",
    summary: "Static documentation with no sensitive data access.",
  },
  {
    id: "asset-5",
    name: "Identity gateway",
    owner: "Identity",
    risk: 88,
    severity: "High",
    summary: "Authentication gateway serving every product surface.",
  },
  {
    id: "asset-6",
    name: "Billing scheduler",
    owner: "Finance",
    risk: 64,
    severity: "Medium",
    summary: "Scheduled billing jobs with restricted network access.",
  },
  {
    id: "asset-7",
    name: "Status page",
    owner: "Reliability",
    risk: 12,
    severity: "Low",
    summary: "Public status surface backed by read-only incident data.",
  },
];

const assetColumns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.original.severity;
      const color =
        severity === "Critical" ? "danger" : severity === "High" ? "warning" : "neutral";
      return (
        <Badge variant={severity === "Critical" ? "solid" : "default"} color={color}>
          {severity}
        </Badge>
      );
    },
  },
];

function DataTableRecipeExample() {
  return (
    <div className="w-full min-w-0">
      <DataTable
        aria-label="Monitored assets"
        columns={assetColumns}
        data={assets.slice(0, 4)}
        pageSize={4}
        showPagination={false}
      />
    </div>
  );
}
```

```tsx
type Asset = {
  id: string;
  name: string;
  owner: string;
  severity: "Critical" | "High" | "Medium" | "Low";
};

const columns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => <Badge>{row.original.severity}</Badge>,
  },
];

<DataTable aria-label="Monitored assets" columns={columns} data={assets} />;
```

Use `cell` when presentation depends on the original row or needs a component. Use column `meta` to align or size headers and cells without coupling those decisions to the generic recipe:

```tsx
{
  accessorKey: "risk",
  header: "Risk score",
  meta: {
    headClassName: "w-32",
    headerContentClassName: "justify-end",
    cellClassName: "text-end tabular-nums",
  },
}
```

## Sorting and pagination

Click a sortable header to cycle through ascending and descending order. Use `defaultSorting` for an initial order. Pagination appears when the row model has more than one page.

```tsx
import { Badge } from "@zentara-co/zenos-ui";
import { DataTable, type DataTableColumnDef } from "@docs/src/recipes/datatable/data-table";

type Asset = {
  id: string;
  name: string;
  owner: string;
  risk: number;
  severity: "Critical" | "High" | "Medium" | "Low";
  summary: string;
};

const assets: Asset[] = [
  {
    id: "asset-1",
    name: "Production API",
    owner: "Platform",
    risk: 96,
    severity: "Critical",
    summary: "Public API with two overdue critical findings.",
  },
  {
    id: "asset-2",
    name: "Customer portal",
    owner: "Web",
    risk: 82,
    severity: "High",
    summary: "Customer-facing application awaiting dependency upgrades.",
  },
  {
    id: "asset-3",
    name: "Analytics worker",
    owner: "Data",
    risk: 58,
    severity: "Medium",
    summary: "Background processor isolated from public traffic.",
  },
  {
    id: "asset-4",
    name: "Documentation",
    owner: "Developer Experience",
    risk: 18,
    severity: "Low",
    summary: "Static documentation with no sensitive data access.",
  },
  {
    id: "asset-5",
    name: "Identity gateway",
    owner: "Identity",
    risk: 88,
    severity: "High",
    summary: "Authentication gateway serving every product surface.",
  },
  {
    id: "asset-6",
    name: "Billing scheduler",
    owner: "Finance",
    risk: 64,
    severity: "Medium",
    summary: "Scheduled billing jobs with restricted network access.",
  },
  {
    id: "asset-7",
    name: "Status page",
    owner: "Reliability",
    risk: 12,
    severity: "Low",
    summary: "Public status surface backed by read-only incident data.",
  },
];

const assetColumns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.original.severity;
      const color =
        severity === "Critical" ? "danger" : severity === "High" ? "warning" : "neutral";
      return (
        <Badge variant={severity === "Critical" ? "solid" : "default"} color={color}>
          {severity}
        </Badge>
      );
    },
  },
];

const sortableAssetColumns: DataTableColumnDef<Asset>[] = [
  ...assetColumns,
  {
    accessorKey: "risk",
    header: "Risk score",
    meta: {
      cellClassName: "text-end tabular-nums",
      headerContentClassName: "justify-end",
    },
  },
];

function DataTableSortingPaginationExample() {
  return (
    <div className="w-full min-w-0">
      <DataTable
        aria-label="Assets ordered by risk"
        columns={sortableAssetColumns}
        data={assets}
        defaultSorting={[{ id: "risk", desc: true }]}
        pageSize={3}
      />
    </div>
  );
}
```

`pageSize` initializes the number of rows per page. For a controlled table, provide `sorting`, `pagination`, and their change callbacks. State callbacks receive resolved state values rather than TanStack updater functions.

## Filtering and column visibility

The recipe owns filter and visibility state, but it intentionally does not prescribe a toolbar. Compose Input, Select, Checkbox, or your feature-specific filters above the table and pass the resulting state in.

```tsx
import { useState } from "react";
import { Badge, Checkbox, Input, Stack, Text } from "@zentara-co/zenos-ui";
import { DataTable, type DataTableColumnDef } from "@docs/src/recipes/datatable/data-table";

type Asset = {
  id: string;
  name: string;
  owner: string;
  risk: number;
  severity: "Critical" | "High" | "Medium" | "Low";
  summary: string;
};

const assets: Asset[] = [
  {
    id: "asset-1",
    name: "Production API",
    owner: "Platform",
    risk: 96,
    severity: "Critical",
    summary: "Public API with two overdue critical findings.",
  },
  {
    id: "asset-2",
    name: "Customer portal",
    owner: "Web",
    risk: 82,
    severity: "High",
    summary: "Customer-facing application awaiting dependency upgrades.",
  },
  {
    id: "asset-3",
    name: "Analytics worker",
    owner: "Data",
    risk: 58,
    severity: "Medium",
    summary: "Background processor isolated from public traffic.",
  },
  {
    id: "asset-4",
    name: "Documentation",
    owner: "Developer Experience",
    risk: 18,
    severity: "Low",
    summary: "Static documentation with no sensitive data access.",
  },
  {
    id: "asset-5",
    name: "Identity gateway",
    owner: "Identity",
    risk: 88,
    severity: "High",
    summary: "Authentication gateway serving every product surface.",
  },
  {
    id: "asset-6",
    name: "Billing scheduler",
    owner: "Finance",
    risk: 64,
    severity: "Medium",
    summary: "Scheduled billing jobs with restricted network access.",
  },
  {
    id: "asset-7",
    name: "Status page",
    owner: "Reliability",
    risk: 12,
    severity: "Low",
    summary: "Public status surface backed by read-only incident data.",
  },
];

const assetColumns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.original.severity;
      const color =
        severity === "Critical" ? "danger" : severity === "High" ? "warning" : "neutral";
      return (
        <Badge variant={severity === "Critical" ? "solid" : "default"} color={color}>
          {severity}
        </Badge>
      );
    },
  },
];

function DataTableFilteringVisibilityExample() {
  const [query, setQuery] = useState("");
  const [showOwner, setShowOwner] = useState(true);

  return (
    <Stack gap="4" className="w-full min-w-0">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Input
          aria-label="Filter assets by name"
          placeholder="Filter assets..."
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          className="max-w-sm"
        />
        <label className="flex items-center gap-2">
          <Checkbox
            aria-label="Show owner column"
            checked={showOwner}
            onCheckedChange={(checked) => setShowOwner(checked === true)}
          />
          <Text size="s">Show owner</Text>
        </label>
      </div>
      <DataTable
        aria-label="Filterable assets"
        columns={assetColumns}
        data={assets}
        columnFilters={query ? [{ id: "name", value: query }] : []}
        columnVisibility={{ owner: showOwner }}
        emptyContent="No assets match this filter."
        showPagination={false}
      />
    </Stack>
  );
}
```

Column filters use TanStack column IDs. In the example, the search Input controls the `name` filter while the Checkbox controls whether the `owner` column is visible.

```tsx
<DataTable
  columns={columns}
  data={assets}
  columnFilters={query ? [{ id: "name", value: query }] : []}
  columnVisibility={{ owner: showOwner }}
  emptyContent="No assets match this filter."
/>
```

## Row selection

Selection UI belongs in a display column. Keep the default Checkbox size, wrap it in a flex container to avoid inline baseline offset, and reduce the selection cells' vertical padding when rows need to remain compact. Use `getRowId` when selections must remain stable across sorting, filtering, pagination, or refreshed data. Without it, TanStack uses positional row IDs.

```tsx
import { useState } from "react";
import { Badge, Checkbox, Stack, Text } from "@zentara-co/zenos-ui";
import { DataTable, type DataTableColumnDef } from "@docs/src/recipes/datatable/data-table";

type Asset = {
  id: string;
  name: string;
  owner: string;
  risk: number;
  severity: "Critical" | "High" | "Medium" | "Low";
  summary: string;
};

const assets: Asset[] = [
  {
    id: "asset-1",
    name: "Production API",
    owner: "Platform",
    risk: 96,
    severity: "Critical",
    summary: "Public API with two overdue critical findings.",
  },
  {
    id: "asset-2",
    name: "Customer portal",
    owner: "Web",
    risk: 82,
    severity: "High",
    summary: "Customer-facing application awaiting dependency upgrades.",
  },
  {
    id: "asset-3",
    name: "Analytics worker",
    owner: "Data",
    risk: 58,
    severity: "Medium",
    summary: "Background processor isolated from public traffic.",
  },
  {
    id: "asset-4",
    name: "Documentation",
    owner: "Developer Experience",
    risk: 18,
    severity: "Low",
    summary: "Static documentation with no sensitive data access.",
  },
  {
    id: "asset-5",
    name: "Identity gateway",
    owner: "Identity",
    risk: 88,
    severity: "High",
    summary: "Authentication gateway serving every product surface.",
  },
  {
    id: "asset-6",
    name: "Billing scheduler",
    owner: "Finance",
    risk: 64,
    severity: "Medium",
    summary: "Scheduled billing jobs with restricted network access.",
  },
  {
    id: "asset-7",
    name: "Status page",
    owner: "Reliability",
    risk: 12,
    severity: "Low",
    summary: "Public status surface backed by read-only incident data.",
  },
];

const assetColumns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.original.severity;
      const color =
        severity === "Critical" ? "danger" : severity === "High" ? "warning" : "neutral";
      return (
        <Badge variant={severity === "Critical" ? "solid" : "default"} color={color}>
          {severity}
        </Badge>
      );
    },
  },
];

const selectableAssetColumns: DataTableColumnDef<Asset>[] = [
  {
    id: "select",
    enableSorting: false,
    header: ({ table }) => (
      <div className="flex items-center">
        <Checkbox
          aria-label="Select all assets on this page"
          checked={
            table.getIsAllPageRowsSelected()
              ? true
              : table.getIsSomePageRowsSelected()
                ? "indeterminate"
                : false
          }
          onCheckedChange={(checked) => table.toggleAllPageRowsSelected(checked === true)}
        />
      </div>
    ),
    cell: ({ row }) => (
      <div className="flex items-center">
        <Checkbox
          aria-label={`Select ${row.original.name}`}
          checked={row.getIsSelected()}
          onCheckedChange={(checked) => row.toggleSelected(checked === true)}
        />
      </div>
    ),
    meta: { cellClassName: "w-12 py-1.5", headClassName: "w-12 py-1.5" },
  },
  ...assetColumns,
];

function DataTableSelectionExample() {
  const [rowSelection, setRowSelection] = useState<Record<string, true>>({});
  const selectedCount = Object.keys(rowSelection).length;

  return (
    <Stack gap="3" className="w-full min-w-0">
      <DataTable
        aria-label="Selectable assets"
        columns={selectableAssetColumns}
        data={assets.slice(0, 4)}
        getRowId={(asset) => asset.id}
        rowSelection={rowSelection}
        onRowSelectionChange={setRowSelection}
        showPagination={false}
      />
      <Text color="subtle" size="s" aria-live="polite">
        {selectedCount} of 4 assets selected.
      </Text>
    </Stack>
  );
}
```

Use `table.toggleAllPageRowsSelected` for a page-level header checkbox. Use `table.toggleAllRowsSelected` only when selecting every filtered row across all client-side pages is the intended behavior.

## Expandable rows

Set `expandable` and provide `renderExpandedRow` to reveal supporting detail without adding more columns. By default, the recipe appends a dedicated expansion control with `aria-expanded`. Set `expanderPosition="start"` to prepend it, and use `expanderButtonClassName` for table-specific control styling.

```tsx
import { Badge, Stack, Text } from "@zentara-co/zenos-ui";
import { DataTable, type DataTableColumnDef } from "@docs/src/recipes/datatable/data-table";

type Asset = {
  id: string;
  name: string;
  owner: string;
  risk: number;
  severity: "Critical" | "High" | "Medium" | "Low";
  summary: string;
};

const assets: Asset[] = [
  {
    id: "asset-1",
    name: "Production API",
    owner: "Platform",
    risk: 96,
    severity: "Critical",
    summary: "Public API with two overdue critical findings.",
  },
  {
    id: "asset-2",
    name: "Customer portal",
    owner: "Web",
    risk: 82,
    severity: "High",
    summary: "Customer-facing application awaiting dependency upgrades.",
  },
  {
    id: "asset-3",
    name: "Analytics worker",
    owner: "Data",
    risk: 58,
    severity: "Medium",
    summary: "Background processor isolated from public traffic.",
  },
  {
    id: "asset-4",
    name: "Documentation",
    owner: "Developer Experience",
    risk: 18,
    severity: "Low",
    summary: "Static documentation with no sensitive data access.",
  },
  {
    id: "asset-5",
    name: "Identity gateway",
    owner: "Identity",
    risk: 88,
    severity: "High",
    summary: "Authentication gateway serving every product surface.",
  },
  {
    id: "asset-6",
    name: "Billing scheduler",
    owner: "Finance",
    risk: 64,
    severity: "Medium",
    summary: "Scheduled billing jobs with restricted network access.",
  },
  {
    id: "asset-7",
    name: "Status page",
    owner: "Reliability",
    risk: 12,
    severity: "Low",
    summary: "Public status surface backed by read-only incident data.",
  },
];

const assetColumns: DataTableColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset" },
  { accessorKey: "owner", header: "Owner" },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.original.severity;
      const color =
        severity === "Critical" ? "danger" : severity === "High" ? "warning" : "neutral";
      return (
        <Badge variant={severity === "Critical" ? "solid" : "default"} color={color}>
          {severity}
        </Badge>
      );
    },
  },
];

function DataTableExpandableRowsExample() {
  return (
    <div className="w-full min-w-0">
      <DataTable
        aria-label="Assets with details"
        columns={assetColumns}
        data={assets.slice(0, 4)}
        getRowId={(asset) => asset.id}
        expandable
        expanderPosition="start"
        renderExpandedRow={(row) => (
          <Stack gap="1">
            <Text weight="medium">{row.original.name}</Text>
            <Text color="subtle" size="s">
              {row.original.summary}
            </Text>
          </Stack>
        )}
        showPagination={false}
      />
    </div>
  );
}
```

Use `getRowCanExpand` when only some rows have details. Set `expandOnRowClick` when the full row should toggle; interactive descendants such as links, buttons, and form controls remain independent.

## Row actions

Add actions as a display column and disable sorting for that column. Read the domain value from `row.original`:

```tsx
const columns: DataTableColumnDef<Asset>[] = [
  // Data columns...
  {
    id: "actions",
    enableSorting: false,
    header: () => null,
    cell: ({ row }) => (
      <Button variant="ghost" size="sm" onClick={() => openAsset(row.original.id)}>
        View
      </Button>
    ),
    meta: { headClassName: "w-20", cellClassName: "text-end" },
  },
];
```

Keep destructive actions behind confirmation and stop propagation when an action is nested inside a clickable row.

## Loading and empty states

Use `isLoading` while the current query is unresolved. `loadingRows` controls the skeleton row count; it defaults to the active page size. Empty content appears after filtering or whenever the supplied dataset has no visible rows.

```tsx
<DataTable columns={columns} data={[]} isLoading loadingRows={6} />

<DataTable
  columns={columns}
  data={[]}
  emptyContent="No assets match the current filters."
/>
```

Do not replace existing rows with loading skeletons during a background refresh unless the data is no longer valid. A separate progress indicator is usually less disruptive.

## Controlled and server-side state

Every interactive state supports controlled and uncontrolled usage. Use the `default*` props for local initial state. Use the state prop and matching callback when URL parameters, feature state, or a server query owns it.

For server-side data, enable the matching manual modes and pass the total page or row information returned by the API:

```tsx
<DataTable
  columns={columns}
  data={query.data.rows}
  sorting={sorting}
  pagination={pagination}
  columnFilters={filters}
  onSortingChange={setSorting}
  onPaginationChange={setPagination}
  onColumnFiltersChange={setFilters}
  manualSorting
  manualFiltering
  manualPagination
  pageCount={query.data.pageCount}
  rowCount={query.data.rowCount}
/>
```

The recipe does not fetch data. Put requests, caching, and query invalidation in a focused feature hook and pass the resolved rows and state into DataTable.

## API

### Data and behavior

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| columns | DataTableColumnDef<TData>[] | — | TanStack column definitions with Zenos cell and header metadata. |
| data | TData[] | — | Rows supplied to the table engine. |
| getRowId | (row, index, parent?) => string | — | Returns a stable row identifier for selection and expansion. |
| onRowClick | (row) => void | — | Makes data rows keyboard- and pointer-activatable. |
| emptyContent | ReactNode | No results. | Content rendered when the active row model is empty. |
| isLoading / loadingRows | boolean / number | — | Shows skeleton rows and controls their count. |
| showPagination / pageSize | boolean / number | true / 10 | Controls pagination visibility and the initial client-side page size. |

### State

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| sorting / defaultSorting | SortingState | — | Controlled or initial sort state. |
| columnFilters / defaultColumnFilters | ColumnFiltersState | — | Controlled or initial column filter state. |
| columnVisibility / defaultColumnVisibility | ColumnVisibilityState | — | Controlled or initial visible-column state. |
| pagination / defaultPagination | PaginationState | — | Controlled or initial page index and page size. |
| rowSelection / defaultRowSelection | RowSelectionState | — | Controlled or initial selected-row map. |
| expanded / defaultExpanded | ExpandedState | — | Controlled or initial expanded-row state. |
| on*Change | (nextState) => void | — | Matching callbacks for each controlled state prop. |

### Expansion and server modes

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| expandable / expandOnRowClick | boolean / boolean | — | Enables expanded content and optionally toggles it from the full row. |
| renderExpandedRow | (row) => ReactNode | — | Renders content below an expanded data row. |
| expanderPosition | "start" \| "end" | end | Places the dedicated expansion-control column before or after data columns. |
| expanderButtonClassName | string | — | Adds classes to each dedicated expansion button. |
| getRowCanExpand | (row) => boolean | — | Restricts expansion to eligible rows. |
| manualSorting / manualFiltering / manualPagination | boolean | — | Delegates the matching row operation to the consumer or server. |
| pageCount / rowCount | number | — | Server-provided totals used by manual pagination. |

## Accessibility

- Give every DataTable an accessible name with `aria-label` or `aria-labelledby`.
- Sortable headers expose buttons and update `aria-sort` on their column headers.
- Label selection checkboxes with the row identity, not only “Select row.”
- Interactive rows respond to Enter and Space. Nested controls do not trigger the row action.
- Expansion controls expose their state with `aria-expanded`.
- Announce selection totals or bulk-action availability with a polite live region.
- Keep essential information in visible cells; expanded content should supplement rather than replace the row.

Virtualization, server caching, drag-and-drop columns, and spreadsheet editing remain outside the baseline recipe. Add them in a feature-owned wrapper when the dataset and interaction model require them.

Source: https://zenos-ui.pages.dev/recipes/data-table/