# Data Table

A table of records with search, sorting, paging, tick boxes and a menu to hide columns. The Table with a little state in front of it; no table library.

Docs: https://ballpoint.st9wd.com/docs/data-table

```bash
npx shadcn@latest add @ballpoint/data-table
```

```tsx
import { DataTable, type DataTableColumn } from "@/components/ui/data-table"

const columns: DataTableColumn<Payment>[] = [
  { id: "email", header: "Email", sortable: true },
  { id: "amount", header: "Amount", sortable: true, align: "right" },
]

<DataTable columns={columns} data={payments} search selectable />
```

Props:

- `columns`: `DataTableColumn<T>[]`. id (the row's field), header, and optionally accessor, cell, sortable, searchable, hideable, align.
- `data`: `T[]`. The rows.
- `getRowId`: `(row, index) => string` (default `index`). A stable key for each row. Needed to keep selection when data changes.
- `pageSize`: `number | false` (default `10`). Rows to a page, or false for no paging.
- `search`: `boolean | string` (default `false`). A search field over every searchable column. A string sets its placeholder.
- `selectable / onSelectionChange`: `boolean / (rows: T[]) => void` (default `false`). A tick box on every row and one for the page, and what is ticked.
- `columnMenu`: `boolean` (default `false`). A Columns menu to hide and show columns.
- `defaultSort`: `{ id: string; dir: 'asc' | 'desc' }`. How it opens.
- `toolbar / empty / caption`: `ReactNode / ReactNode / string`. More for the bar above; what to say when no row matches; a name for screen readers.

## Example

```tsx
"use client";

import { Badge } from "@/components/ui/badge";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";

type Payment = { id: string; status: "pending" | "processing" | "success" | "failed"; email: string; amount: number };

const payments: Payment[] = [
  { id: "m5gr84i9", status: "success", email: "ken99@example.com", amount: 316 },
  { id: "3u1reuv4", status: "success", email: "abe45@example.com", amount: 242 },
  { id: "derv1ws0", status: "processing", email: "monserrat44@example.com", amount: 837 },
  { id: "5kma53ae", status: "success", email: "silas22@example.com", amount: 874 },
  { id: "bhqecj4p", status: "failed", email: "carmella@example.com", amount: 721 },
  { id: "p0ak2m1x", status: "pending", email: "jules@example.com", amount: 129 },
  { id: "q9w8e7r6", status: "success", email: "ines@example.com", amount: 460 },
  { id: "z1x2c3v4", status: "processing", email: "otto@example.com", amount: 98 },
];

const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

const columns: DataTableColumn<Payment>[] = [
  {
    id: "status",
    header: "Status",
    sortable: true,
    cell: (row) => (
      <Badge variant={row.status === "failed" ? "destructive" : row.status === "success" ? "default" : "secondary"} size="sm" seed={`dt-${row.id}`}>
        {row.status}
      </Badge>
    ),
  },
  { id: "email", header: "Email", sortable: true },
  { id: "amount", header: "Amount", sortable: true, align: "right", cell: (row) => money.format(row.amount) },
];

export default function DataTableDemo() {
  return (
    <div className="w-full max-w-2xl">
      <DataTable columns={columns} data={payments} getRowId={(row) => row.id} pageSize={5} search="Filter emails…" selectable columnMenu caption="Payments" />
    </div>
  );
}
```

## Sorting only

No toolbar and no paging, opening sorted by one column.

```tsx
"use client";

import { DataTable, type DataTableColumn } from "@/components/ui/data-table";

type Pen = { name: string; kind: string; weight: number };

const pens: Pen[] = [
  { name: "Blue ballpoint", kind: "Ink", weight: 0.7 },
  { name: "Black gel", kind: "Ink", weight: 0.5 },
  { name: "HB pencil", kind: "Graphite", weight: 0.9 },
  { name: "Felt tip", kind: "Ink", weight: 1.2 },
  { name: "Charcoal", kind: "Charcoal", weight: 3 },
];

const columns: DataTableColumn<Pen>[] = [
  { id: "name", header: "Pen", sortable: true },
  { id: "kind", header: "Kind", sortable: true },
  { id: "weight", header: "Line (mm)", sortable: true, align: "right" },
];

export default function DataTableSimple() {
  return (
    <div className="w-full max-w-lg">
      <DataTable columns={columns} data={pens} pageSize={false} defaultSort={{ id: "weight", dir: "desc" }} />
    </div>
  );
}
```

## Row actions

A menu on every row; the data is yours, so removing a row is a state change.

```tsx
"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { InkIcon } from "@/components/ui/ink-icons";

type Note = { id: number; title: string; edited: string };

const initial: Note[] = [
  { id: 1, title: "Letter to Ada", edited: "Today" },
  { id: 2, title: "Margin sketches", edited: "Yesterday" },
  { id: 3, title: "Shopping list", edited: "Monday" },
];

export default function DataTableActions() {
  const [notes, setNotes] = useState(initial);
  const columns: DataTableColumn<Note>[] = [
    { id: "title", header: "Note", sortable: true },
    { id: "edited", header: "Edited" },
    {
      id: "actions",
      header: <span className="sr-only">Actions</span>,
      hideable: false,
      searchable: false,
      align: "right",
      cell: (note) => (
        <DropdownMenu>
          <DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Actions for ${note.title}`} seed={`dta-${note.id}`} />}>
            <InkIcon name="more" />
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => navigator.clipboard?.writeText(note.title)}>Copy title</DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem variant="destructive" onClick={() => setNotes((all) => all.filter((n) => n.id !== note.id))}>
              Delete
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];
  return (
    <div className="w-full max-w-lg">
      <DataTable columns={columns} data={notes} getRowId={(note) => String(note.id)} pageSize={false} empty="No notes left." />
    </div>
  );
}
```
