Search documentation

Search pages, components, blocks, styles and colours.

Get started
Skip to content

Data Table

PreviousNext

Typed columns, sorting, Notion-style filters, cells that edit in place, and ten thousand rows that load as you scroll, on TanStack Table.

0 selected

The demo reads 10,000 accounts from a stand-in server, 100 at a time as they come into view: the scroll covers all of them, so drag it anywhere and that window arrives, with skeleton rows meanwhile. Click a header to sort it (Shift adds a second sort), open its options to filter, pin or hide it, drag its edge to resize, and pick rows with their checkboxes (Shift picks a range). Click a cell to edit it. The settings at the end of the header set the density, the calculations, row numbers, stripes, column lines and which columns show. The footer's calculations cover every matching account; click one to change it.

Data Table is part of the Fabricator style. It draws a TanStack Table v9 instance as one real <table> in a scrolling frame: the header and footer stick, pinned columns stay at either edge, and only the rows in view are in the DOM, through TanStack Virtual. Each column's meta.type picks its cell, its filter, its editor, its sort, its alignment and its calculations, so a page describes its columns and the table does the rest. Popovers, menus, switches, checkboxes, badges and avatars are the library's own components.

Installation

bunx --bun fabricator-ui@latest add data-table

Usage

import {
  createDataTableColumnHelper,
  useDataTable,
  type DataTablePage,
  type DataTableQuery,
} from "@/hooks/use-data-table"
import {
  createDataTableSelectColumn,
  DataTable,
  DataTableContent,
  DataTableSearch,
  DataTableToolbar,
} from "@/components/ui/data-table"
type Deal = { id: string; company: string; stage: string; value: number }
 
const column = createDataTableColumnHelper<Deal>()
 
const columns = column.columns([
  createDataTableSelectColumn<Deal>(),
  column.accessor("company", {
    meta: { type: "text", label: "Company", primary: true, pin: "start" },
  }),
  column.accessor("stage", {
    meta: {
      type: "status",
      label: "Stage",
      editable: true,
      options: [
        { value: "open", label: "Open", tone: "info" },
        { value: "won", label: "Won", tone: "success" },
        { value: "lost", label: "Lost", tone: "destructive" },
      ],
    },
  }),
  column.accessor("value", {
    meta: { type: "currency", label: "Value", aggregate: "sum" },
  }),
])
 
async function loadDeals(
  query: DataTableQuery,
  signal: AbortSignal
): Promise<DataTablePage<Deal>> {
  const response = await fetch("/api/deals", {
    method: "POST",
    body: JSON.stringify(query),
    signal,
  })
  return response.json()
}
 
export function Deals() {
  const table = useDataTable({
    columns,
    load: loadDeals,
    getRowId: (deal) => deal.id,
    onCellChange: async ({ row, columnId, value, replaceRow }) => {
      const deal = { ...row, [columnId]: value }
      replaceRow?.(deal)
      await saveDeal(deal)
    },
  })
 
  return (
    <DataTable className="h-[560px]">
      <DataTableToolbar>
        <DataTableSearch table={table} />
      </DataTableToolbar>
      <DataTableContent table={table} />
    </DataTable>
  )
}

Keep columns outside the component (or memoize it), and give the table a height: rows scroll inside DataTableContent, which fills a DataTable with a height or takes one of its own.

Rows already in memory go in data instead of load: the table sorts, filters and searches them itself.

const table = useDataTable({
  data: deals,
  columns,
  getRowId: (deal) => deal.id,
})

Loading rows

load is the recommended way to feed the table. It's called with a window of rows and the view that orders them, and returns those rows and how many match in all:

type DataTableQuery = {
  offset: number
  limit: number // pageSize, 100 by default
  sorting: { id: string; desc: boolean }[]
  filters: { id: string; value: DataTableFilter }[]
  search: string
}
 
type DataTablePage<Row> = {
  rows: Row[]
  total: number
  aggregates?: Record<
    string,
    Partial<Record<DataTableAggregate, number | null>>
  >
}
  • The scroll covers every match. The first window loads with skeleton rows, and from then on the scroll is as long as total: every row not loaded yet is a skeleton row in its place. The windows in view load as the scroll reaches them, with a quarter of a window either side, so dragging the scrollbar to row 8,000 asks for that window alone. A slow scroll asks at once; a fast one asks when it settles and drops requests it has passed. If a window fails, its first row in view says so with a "Try again".
  • A new view starts over. A new sort, filter or search asks for the first window again; the rows dim under a bar until it arrives. The search waits 250ms after the last keystroke, and a request the table no longer needs is aborted through signal.
  • Pages instead of a scroll. Pass paginate and add DataTablePagination; each page is one request.
  • The footer covers every match. Send aggregates with the first window, and the footer shows them instead of figures over the loaded rows.

The model answers a query the way the table would, so a server written in TypeScript can use it as is:

import { queryRows, summarizeRows } from "@/lib/data-table-model"
 
const fields = {
  company: { type: "text" },
  stage: { type: "status", options: STAGES },
  value: { type: "currency" },
} as const
 
function read(deal: Deal, id: string) {
  return id === "company" || id === "stage" || id === "value"
    ? deal[id]
    : undefined
}
 
export function answer(query: DataTableQuery) {
  const matching = queryRows(deals, query, fields, read)
  return {
    rows: matching.slice(query.offset, query.offset + query.limit),
    total: matching.length,
    aggregates: summarizeRows(matching, fields, read),
  }
}

A database query reads the same filters: each value is a DataTableFilter, { operator, value?, to?, preset? }, listed under Filters.

Columns

Columns are TanStack column definitions. createDataTableColumnHelper is TanStack's helper typed for the Data Table, and meta tells the table what each column holds.

Types

meta.typeValueCellEditorCalculations
textstringText, truncatedAn inputCount, filled, empty, unique
numbernumberTabular figures, at the endAn inputSum, average, median, min, max
currencynumberMoney in format.currency (USD)An inputSum, average, median, min, max
percentnumber, a fraction0.42 as 42%An input, in percentSum, average, median, min, max
progressnumber, 0 to 100A Progress bar and its valueAn inputSum, average, median, min, max
dateDate, ISO string, or msNov 3, 2026, or "3 days ago"A CalendarCount, filled, empty, min, max
statusstring, one of optionsA Badge in the option's tone, with a dotA pickerCount, filled, empty, unique
tagsstring[] of optionsEvery Badge, scrolling sideways with a fadeA picker that togglesCount, filled, empty, unique
personstring, one of optionsAn Avatar (option.image) and the nameA pickerCount, filled, empty, unique
linkURL stringThe host, opening in a new tabAn input, and an open linkCount, filled, empty, unique
emailstringA mailto: linkAn input, and an open linkCount, filled, empty, unique
booleanbooleanA check or a dash; a Checkbox when editableThe CheckboxCount, checked, unchecked

Statuses sort in the order of their options, like a pipeline. Numbers and dates sort descending first. Text, status, tags, person, link and email columns answer the search. A picker with more than a handful of options has a search field.

Meta

FieldTypeWhat it does
typesee aboveThe cell, filter, editor, sort, alignment, width and calculations
labelstringThe header, and the column's name in menus
iconComponentTypeReplaces the type's icon in the header
options{ value, label, tone?, image? }[]Values of a status, tags or person column; tone colours the Badge
format{ currency, compact, fractionDigits, relative }How numbers and dates read
aggregate"count" | "sum" | "average" | …The footer's calculation; people can change it
editablebooleanCells edit in place; needs onCellChange
primarybooleanThe record's name: foreground and medium weight
pin"start" | "end"Pins the column on first render
align"start" | "center" | "end"Overrides the type's alignment of cells and the footer; heads always read from the start

tone is neutral, info, success, warning or destructive, the Badge's status colours.

Filters

Each column's options hold a filter as Notion has them: a condition, and the value it calls for.

KindConditions
Text, link, emailContains, does not contain, is, is not, starts with, ends with, is empty, is not empty
Number, currency, percent=, ≠, >, ≥, <, ≤, is between, is empty, is not empty
DateIs within (today, yesterday, past week, month or year, this month or year, next week or month), is, is before, is after, is on or before, is on or after, is between, is empty, is not empty
Status, personIs any of, is none of, is empty, is not empty, from a checklist
TagsHas any of, has all of, has none of, is empty, is not empty
BooleanAll, checked, unchecked

With rows in memory, the checklist counts each option and the number filter shows the range in view. Set one in code with the column's filter value, { operator: "anyOf", value: ["won"] }, or through initialState.columnFilters.

Custom cells

Give a column a cell to draw it yourself. DataTableValue from data-table-cells draws one value the way a type does, so a custom cell can keep the look:

column.accessor("company", {
  meta: { type: "text", label: "Company" },
  cell: ({ row, getValue }) => (
    <span className="flex items-center gap-2">
      <img src={row.original.logo} alt="" className="size-5 rounded" />
      <DataTableValue type="text" value={getValue()} />
    </span>
  ),
})

A custom cell redraws when its row's data changes, not on every change to the table. One that shows table state, such as whether its row is picked, reads it through TanStack's Subscribe:

import { Subscribe } from "@tanstack/react-table"
 
cell: ({ row, table }) => (
  <Subscribe source={table.store} selector={(state) => state.rowSelection}>
    {() => (row.getIsSelected() ? "Picked" : "")}
  </Subscribe>
)

Selection and actions

createDataTableSelectColumn() adds the checkbox column, pinned to the start. With row numbers on, each row shows its place until it's lit or picked. A display column with meta: { kind: "actions" } is pinned to the end and sized for one icon button, usually a Dropdown Menu. Its header holds the table's settings. A table without an actions column gets an empty one to hold them, so everything but the search happens inside the table.

Editing

Mark columns editable and pass onCellChange. A click on a cell opens the editor its type calls for, as in a Notion table:

  • Text, numbers, links and emails edit in an input. Enter or Tab saves, Escape cancels. On a focused cell, typing starts over with what you type, and F2 or Enter edits what's there.
  • Statuses and people open a picker; picking the current option clears it. Tags toggle in the same picker.
  • Dates open a Calendar. Checkboxes toggle.

onCellChange gets { row, rowId, columnId, value }. Values arrive parsed: numbers as numbers, percents as fractions, dates in the shape the row had them. With load, call replaceRow with the updated row to show it at once, then save it. With data, update your state; the table keeps its page and scroll.

const [deals, setDeals] = React.useState(initialDeals)
const table = useDataTable({
  data: deals,
  columns,
  onCellChange: ({ rowId, columnId, value }) =>
    setDeals((current) =>
      current.map((deal) =>
        deal.id === rowId ? { ...deal, [columnId]: value } : deal
      )
    ),
})

Settings

The button at the end of the header opens the table's settings: density (compact, default, comfortable), switches for calculations, row numbers, striped rows and column lines, the columns to show, and clearing the sort and filters or resetting the columns. They're the table's view; set it with defaultView, or control it with view and onViewChange.

<DataTable defaultView={{ numbered: true, footer: false, size: "sm" }}>

Composition

DataTable                      frame, variant, view
├── DataTableToolbar
│   └── DataTableSearch        the global search
├── DataTableContent           the scrolling table
│   ├── header                 sort, type icon, options popover, resize
│   │   └── settings           density, switches, columns, reset
│   ├── virtual rows           cells that edit in place
│   ├── footer                 one calculation per column, optional
│   └── DataTableSelectionBar  floats while rows are picked
└── DataTablePagination        with useDataTable({ paginate: true })

Every part takes the table from useDataTable, so each one is typed by your rows. DataTableColumnFilter is the filter editor on its own, for a column filter somewhere else.

Examples

Pagination

Pass paginate to useDataTable and add DataTablePagination: rows per page, the range in view and page buttons. The rows here are in memory and editable; an edit keeps the page.

INV-04000
INV-04001
INV-04002
INV-04003
INV-04004
INV-04005
INV-04006
INV-04007
INV-04008
INV-04009
Rows per page

1–10 of 1,000

Server pages

load with paginate: each page is a request, the rows dim under a bar while the next page loads, and the footer's sum comes from the server.

Rows per page

0–0 of 0

States

Without a loader, DataTableContent takes the states as props. loading without rows draws skeleton rows; with rows it dims them under a bar. With no rows the table shows an Empty, which offers to clear the filters when they caused it; pass empty to replace it. error takes the rows' place.

Variants

variant frames the table on a card or leaves it flat on the page. The view is controlled here, so the toggles above and the table's settings stay in step.

Studio HeadphonesAudio$349.004242%Yes
Desk SpeakerAudio$199.00038%No
Smart RingWearables$299.001855%Yes
Fitness BandWearables$89.0012031%Yes
Air PurifierHome$249.00727%Yes
Floor LampHome$129.003344%No
USB-C Cable 2mCables$19.0086071%Yes
Braided Lightning CableCables$29.0041266%Yes
Noise Cancelling EarbudsAudio$179.006448%Yes
Sleep TrackerWearables$149.002552%No

API Reference

useDataTable

Every TanStack useTable option except features, plus:

OptionTypeDefault
load(query, signal) => Promise<Page>-Rows a window at a time; the recommended source
dataTData[]-Rows in memory, instead of load
columnsColumnDef[]-Keep them stable: outside the component or memoized
getRowId(row) => stringthe indexKeeps selection, edits and scroll stable
pageSizenumber100Rows load asks for at a time while scrolling
paginatebooleanfalsePages instead of one scroll
onCellChange({ row, rowId, columnId, value, replaceRow }) => void-An edited cell's new value
manualbooleanfalsedata is already sorted, filtered and paged; pass rowCount
localestring"en-US"Numbers and dates
nownumberwhen it mountedWhat relative dates count from

It returns the TanStack table. The sort, filters, search and page live in the hook so a change can reload and go back to the first page; pass them in state with on…Change to control them.

DataTable

PropTypeDefault
variant"card" | "flat""card"
defaultViewPartial<DataTableView>-
viewPartial<DataTableView>-
onViewChange(view: DataTableView) => void-

DataTableView is { size?: "sm" \| "default" \| "lg", lines: "rows" \| "grid", striped: boolean, footer: boolean, numbered: boolean }; by default rows, no stripes, the footer on and no numbers, at the page's density.

DataTableContent

PropTypeDefault
tablethe table-
loadingbooleanfrom the loader
loadingMorebooleanfalse
hasMorebooleanfalse
onLoadMore() => void-
loadMoreThresholdnumber20
overscannumber5
emptyReactNodean Empty
errorReactNodefrom the loader
onRowClick(row) => void-

DataTablePagination

PropTypeDefault
tablethe table-
pageSizesnumber[][10, 25, 50, 100]

Other parts

DataTableSearch takes the table and Search's props. DataTableSelectionBar takes the table and the actions as children.

Data attributes

AttributeElementPresent when
data-slot="data-table-row"each rowalways
data-state="selected"a rowit's picked
data-pinned="start" | "end"a cell or headits column is pinned
data-editablea cellits column edits
data-slot="data-table-sort"a head's sort buttonthe column sorts
data-sorted="asc" | "desc"a sort buttonthe column is sorted
data-slot="data-table-column-trigger"a head's optionsthe column has options
data-filtereda head's optionsthe column filters
data-slot="data-table-settings-trigger"the settings buttonalways
data-lines="rows" | "grid", data-stripedthe rootthe view says so
data-state="open" | "closed"the selection barrows are picked

Accessibility

  • It's a table, not a grid: every control stays in the tab order, as in the WAI-ARIA sortable table pattern. Heads carry aria-sort, rows aria-rowindex against the table's aria-rowcount, so screen readers count all rows, not only those in the DOM.
  • Each head's sort button is named by its label, and its options button "Label options". The settings button is "Table settings", and each switch is named by its label.
  • An editable cell is a button named by its value; its editor is labelled by the column. Focus returns to the cell when the editor closes.
  • The resize edge is a focusable separator with its width as its value: Left and Right resize by 16px, with Shift by 48px. Double-click resets it.
  • Checkboxes are named "Select row N" and "Select all rows"; Shift with a click or Space picks a range. The selection bar announces the count.
  • With onRowClick, rows are focusable and Enter activates them; clicks on buttons, links and checkboxes inside a row don't.

Performance

The table is built to stay smooth with tens of thousands of rows and a page that re-renders around it:

  • Rows. Only the rows in view, and overscan rows around them, are in the DOM. Rows have a fixed height, so the virtualizer never measures them.
  • Redraws. Each row, each cell, the header and the footer redraw only when what they show changes. Picking a row redraws its checkbox, not its badges and avatars. The select-all checkbox and the resize handles follow their own slice of state through Subscribe, so a selection or a drag doesn't redraw the header. Footer figures are worked out again only when the rows or the calculations change.
  • Resizing. Widths go on the <col>s and pinned offsets in a rule that matches the pinned cells only, so a drag lays the table out again without restyling its cells. The viewport is layout- and paint-contained.
  • Light parts per row. The checkboxes in rows are drawn on plain buttons with the Checkbox's look. Avatar pictures are plain images over the initials. Editors, pickers and menus mount their popover the first time they open.
  • Data. With load, the browser holds only the windows it has scrolled through. With data, sorting, filtering and the search run in TanStack's memoized row models. The search keeps each cell's text, lowercased, until its row changes, and updates in a transition, so typing stays responsive on 10,000 rows.
  • Scrolling. A fast scroll draws cheap skeleton rows far ahead of itself and the real rows once it slows, so a fling never shows an empty table; the space beyond the rows drawn carries their hairlines. The viewport doesn't bounce or hand its scroll to the page in either direction. With a mouse or trackpad its scrollbars run from under the header to above the footer, and between the pinned columns; touch keeps the system's.