# Data Table

A data table on TanStack Table: sort on several columns, filter from the column definitions, select rows with a floating action bar, expand, pin, resize columns, page and export to CSV, and show rows as cards on small screens, with controlled state for server-side data.

- Category: Data & Tables
- Page: https://wunderui.com/components/data-table
- Tier: Core and Pro

## Install

Data Table ships with WunderUI Core and Pro in the @wunderui/react package.

## Import

```tsx
import { DataTable, DataGrid, DataTableBulkContext, DataTableColumnDef, DataTableColumnFooter, DataTableColumnMeta, DataTableError, DataTableExpandedState, DataTableExportContext, DataTableFilter, DataTableFilterOption, DataTableFiltersState, DataTableFooterCalculation, DataTablePaginationState, DataTablePinningState, DataTableProps, DataTableQuery, DataTableSelectionState, DataTableServerSide, DataTableSortingState, DataTableState, DataTableUrlStateOptions, DataTableVisibilityState } from "@wunderui/react"
```

## Minimal usage

Then use it:

```tsx
import { DataTable, type DataTableColumnDef } from "@wunderui/react"

type Invoice = { id: string; owner: string; status: "Paid" | "Pending" | "Overdue"; amount: number }

const columns: DataTableColumnDef<Invoice>[] = [
  { accessorKey: "id", header: "Invoice" },
  { accessorKey: "owner", header: "Owner", meta: { filter: { type: "text" } } },
  { accessorKey: "status", header: "Status", meta: { filter: { type: "multiSelect" } } },
  { accessorKey: "amount", header: "Amount", meta: { numeric: true, filter: { type: "number", unit: "USD" } } },
]

// Keep `columns` and `data` stable: module constants, state or useMemo.
const invoices: Invoice[] = [
  { id: "INV-2001", owner: "Nora Lindgren", status: "Paid", amount: 897 },
  { id: "INV-2002", owner: "Daniel Okafor", status: "Pending", amount: 398 },
  { id: "INV-2003", owner: "Priya Raman", status: "Paid", amount: 597 },
]

export function Invoices() {
  return <DataTable aria-label="Invoices" columns={columns} data={invoices} getRowId={(row) => row.id} rowLabel={(row) => row.id} />
}
```

Expected result: You see a card with a search field, Filter, View and Export buttons, sortable columns, three invoice rows with checkboxes and a pager. Tick a row and the selection bar appears.

## When to use

### Use Data Table for

- Rows people work with: sort on several columns, filter, search, select and act on many at once
- Data that lives on a server, paged, sorted and filtered by your API
- A table whose view should survive a reload or a shared link, with a CSV export

### Use something else

- [Table](https://wunderui.com/components/table) for a short list people only read, with the cells of your own markup
- [Filter Menu](https://wunderui.com/components/filter-menu) for one filter control for a list that is not a table

## Keyboard

The table is one grid with one tab stop: Tab enters it once and leaves it once, however many rows there are. The toolbar, chips and pager are ordinary tab stops before and after it.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Enters the grid on the last active cell (the first header cell to begin with) and leaves it on the next Tab. Between the toolbar, the chips, the grid and the pager it moves in reading order. |
| `ArrowRight` or `ArrowLeft` or `ArrowDown` or `ArrowUp` | Moves to the neighbouring cell. At an edge it stays where it is. |
| `Home` or `End` | First or last cell of the row. |
| `Ctrl+Home` or `Ctrl+End` | First or last cell of the grid on this page. |
| `PageUp` or `PageDown` | Ten rows up or down, or to the first or last row. |
| `Enter` or `Space` | Does the main thing of the cell: sorts the column on a header, ticks the checkbox on a row, opens or closes a row with a chevron. A cell with several controls and no main one moves focus into the cell instead. |
| `Shift+Enter` | On a header, adds the column to the sort instead of replacing it. A number then shows the order. |
| `F2` | Moves focus to the first control of the cell, such as the column menu of a header. Tab and Shift+Tab then walk the controls of that cell. |
| `Arrow Left` or `Arrow Right` | On a focused resize handle (reached with F2 from a header cell), makes the column 8 px narrower or wider; with Shift 32 px. Only with resizableColumns. |
| `Home` or `End` | On a focused resize handle, sets the column to its minimum width or back to its start width. Double-click on the handle also resets the column. |
| `Esc` | From a control inside a cell, returns focus to the cell. In an open menu or the filter popover it closes the popup and returns focus to its button. |

## Behavior

What the table does with its state, its rows and its data, and what it leaves to you.

- **State:** Each part of the state (sorting, filters, search, columns, selection, paging, pinning, expanded rows) is controlled when you pass its value and change handler, and kept by the table otherwise.
- **Page resets:** A new sort, filter or search goes back to the first page. If the current page disappears, the table steps back to the last one, except with server paging where you own the page.
- **Query callback:** The query callback fires when the page, order, a filter or the search changes, but not on the first render. It is the one callback to fetch from.
- **Selection:** Selection is kept by row id and survives paging and sorting. The header checkbox ticks the page, shift-click ticks a range, and Select all ticks every filtered row (left out with server paging).
- **Filters and search:** Search covers the text and number columns. Filters can be text, one choice, several choices or a number range, with choices and counts read from the loaded rows unless you list them.
- **Columns:** Columns default to 160 px and the rest of the row is shared. A data column without its own minSize gets one from its header label, so the label, the sort arrow and the column menu always fit, also below a narrow size. A wide table scrolls inside its box, and columns can be hidden or pinned to either end.
- **Column menu:** The chevron of the column menu shows while the header cell is hovered or holds the focus and while the menu is open, and always on touch screens. It only fades (opacity), so it keeps its room and nothing moves, and it stays reachable from the keyboard (F2, then Tab in the header cell).
- **Expanded rows:** An opened panel is as wide as the visible part of the table and sticks to its start edge, so nothing in it is off-screen while a wide table scrolls sideways.
- **Phone cards:** With mobileLayout cards, text fields sit three to a row and truncate with the full text as title. A field whose cell draws more than text (an icon, an image, a control, or a library part such as a badge, avatar or chart) takes the whole row and wraps. Expandable rows keep their toggle in the card and open the panel inside it, and the footer calculations follow as a summary under the cards.
- **Server-side data:** With server-side data the table does not sort, filter or page. It reports the query and shows the data and row count you pass, so keep loading on until the answer arrives.
- **States:** Loading draws skeleton rows, Empty says there is no data, No results offers Reset filters, and Error offers Try again when a retry handler is set. Export is disabled in all four.
- **Announcements:** A hidden status line reads the row count, Loading rows or the error, and the action bar count is a polite live region. The grid also reports row and column counts, selection and sort order.
- **Export:** Export writes a CSV of the visible columns in their order, with header labels and a byte order mark so Excel reads UTF-8. Export selected writes only the selected rows.
- **Limits:** Every row of the current page is rendered and nothing is virtualised, so for very large data use server-side mode. Inline editing and column resizing are not part of the table.
- **Motion:** The action bar fades in and slides up 8 px, and an opened row fades in while its chevron turns. With reduced motion the slide and fades are off and the chevron turns at once.

## Anatomy

- `DataTable`: The whole table in one bordered box: a toolbar, filter chips, the grid, an action bar while rows are selected, and a footer. Its state reads ready, loading, empty or error.
- `Toolbar`: A toolbar named Table tools: search on the left, then Filter, View, Export and any actions you pass in. Each control can be turned off.
- `Search`: The field that filters every row by the text of the text and number columns. A new search goes back to the first page.
- `Filter`: Opens a list of filterable columns. Choosing one opens its editor: a text field, a list of choices or a minimum and maximum, and the button shows how many filters are active.
- `View menu`: A menu of checkboxes that shows and hides columns. It never lets the last visible column go.
- `Export`: Saves every row, after filtering and sorting, as a CSV of the visible columns. It is disabled while loading, on an error and with no rows, and a custom export handler replaces the download.
- `Filter chip`: One chip per active filter: the column, how it matches (is, is any of, contains, between) and the value. The label opens the editor, the cross removes it, and Reset filters clears all.
- `Column header`: A column header with the sort button, a direction icon and, once two columns are sorted, a number for the order. Every sortable header reports its sort order.
- `Column menu`: A small button beside each heading with sort ascending or descending, Then by, Clear sort, Pin to start or end, and Hide column.
- `Row`: One row of cells. It turns page tone on hover and subtle tone while selected, and the first data column is primary text with the rest secondary.
- `Row details`: The panel under an opened row, drawn by a sub row renderer. A chevron column is added when you pass one.
- `Action bar`: A floating bar named Selection actions with the count, your bulk actions, Select all, Export selected and Clear. It sticks to the bottom of the screen while the table runs past it.
- `Footer`: How many rows are selected out of the total, or just the row count when selecting is off.
- `Pager`: Rows per page and the page buttons. Turning paging off removes both and shows every row.
- `Loading, empty and error rows`: Replaces the rows: skeleton rows while loading, an empty state, a No results state with Reset filters, and an error with Try again when you pass a retry handler. Toolbar and header stay.
- `DataGrid`
- `Details Content`
- `Cards View`
- `Cards`
- `Card`
- `Card Expand`
- `Card Field`
- `Card Value`
- `Card Details`
- `Cards Footer`
- `Header Icon`
- `Footer`
- `Status`
- `Footer Menu`
- `Resize`
- `Cards Loading`
- `Cards Empty`

## Best practices

### When to use

- Use a Data Table when people work with the rows: sort on several columns, filter, select for a bulk action or page through server data. For a short list people only read, a Table is lighter.

### Do

- Name the grid with an aria-label and each row with a row label, so a checkbox reads Select INV-2001 instead of Select row 3.
- Pass a stable row id. Selection is kept by id, so without it a selection follows the position of a row when you sort or page.
- Keep columns and data stable: module constants, state or useMemo. A new array on every render makes the table recompute its rows.
- Turn on resizableColumns where people compare long values, and give the first column a start width that fits its longest text. Every column keeps at least 80 px, so a table with many columns scrolls sideways instead of cutting text.
- Pass loading, an error with a retry handler and, where it helps, an empty state. The table draws the skeleton rows, the alert and the empty message itself and keeps the toolbar.
- With server-side data, list the choices of a select filter yourself. The loaded rows are only one page, so reading the choices from them would hide most of them.
- Keep the query in the address bar with the URL state hook, under its own prefix, so a reload or a shared link opens the same view.
- Format footer totals with meta.footerFormat (the same format as the cells), hide the "n rows" line with showRowCount={false} when the footer or the page says it, and set density instead of overriding --row-py.

### Don't

- Don't turn on resizableColumns for a table with two or three short columns. The handles add a focus stop per column and nothing to resize.
- Don't sort, filter or page the rows yourself before passing them in. Let the table do it, or use server-side mode and answer the query callback with the matching page.
- Don't put thousands of rows on one page with paging off. Every row is rendered, because the table does not virtualise.
- Don't rely on the table for inline editing or column resizing. Neither exists; a cell can hold a control, but the table does not manage it.

## API reference

### DataTable

| Prop | Type | Default | Description |
|---|---|---|---|
| columns* | DataTableColumnDef<TData>[] |  | The column definitions. Plain TanStack column objects (`accessorKey`, `header`, `cell`, `size`) or the output of `createDataTableColumnHelper`; collect those with `column.columns([...])` so every `info.getValue()` keeps its accessor's type (a cast to `DataTableColumnDef<T>[]` turns it into `any`). `meta.filter` makes a column filterable, `meta.numeric` right-aligns it, `meta.label` names it in menus, chips and the CSV header, and `meta.exportValue` sets what the CSV writes. Without `minSize`, a data column's minimum width comes from its header label. Keep the reference stable. |
| data* | TData[] | EMPTY_DATA | The rows. Keep the reference stable: a new array on every render makes the table recompute. With `serverSide` this is one page, already in order. |
| aria-label | string |  | The accessible name of the grid. Give every table a distinct one; it is `Data table` by default. |
| bulkActions | (context: DataTableBulkContext<TData>) => React.ReactNode |  | Buttons for the floating bar that appears while rows are selected. It gets the selected rows that are loaded, the ids of every selected row (also on other pages) and `clear()`. |
| className | string |  | Extra classes for the outer box. |
| columnDividers | boolean | false | Draws a thin vertical line between every pair of columns instead of only at the edges of pinned columns. |
| columnFilters | ColumnFiltersState |  | The column filters as TanStack state: `[{ id: "status", value: ["Pending"] }]`. Pass it with `onColumnFiltersChange` to control it. |
| columnFooter | DataTableColumnFooter |  | A footer row under the rows with a calculation per column (count, sum, average, minimum, maximum), picked from a menu in each footer cell. It counts every row after search and filters, on all pages (on server pages, the loaded page). Defau… |
| columnPinning | ColumnPinningState |  | Which columns are pinned: `{ start: ["owner"], end: [] }`. Pass it with `onColumnPinningChange` to control it. The checkbox and expander columns are always first and are not listed. |
| columnVisibility | ColumnVisibilityState |  | Which columns are hidden: `{ plan: false }`. Pass it with `onColumnVisibilityChange` to control it. |
| columnVisibilityMenu | boolean | true | Shows the View menu. Default `true`. |
| density | "compact" \| "default" \| "relaxed" | "default" | Row padding: `compact` (4 px, rows ≈ 29 px), `default` (the `--row-py` density token, 6 px), `relaxed` (14 px, rows ≈ 49 px). Only the rows change; the toolbar and the controls keep their size. |
| emptyState | React.ReactNode |  | Replaces the default No data yet state, which shows when there are no rows and no filter or search is active. |
| error | boolean \| string \| DataTableError |  | Shows the error state instead of the rows. `true` uses the default text, a string becomes the description, an object sets `title` and `description`. |
| expanded | ExpandedState |  | Which rows are open, as TanStack state. Pass it with `onExpandedChange` to control it. |
| exportable | boolean | true | Shows the Export button and Export selected. Default `true`. |
| exportFileName | string | "table" | The name of the CSV file, without the extension. Default `table`. |
| getRowCanExpand | (row: TData) => boolean |  | Which rows can open. Default: all of them. Only read when `renderSubRow` is set. |
| getRowId | (row: TData, index: number) => string |  | Returns a stable id for a row. Selection is kept by this id, so it survives paging and sorting; without it the id is the row index. |
| globalFilter | string |  | The search text. Pass it with `onGlobalFilterChange` to control it. |
| initialState | Partial<DataTableState> |  | Starting values for the state you do not control: `pagination`, `sorting`, `columnFilters`, `globalFilter`, `columnVisibility`, `rowSelection`, `columnPinning` and `expanded`. It is read once. |
| loading | boolean | false | Shows skeleton rows in place of the rows, sets `aria-busy` and announces Loading rows. Export is disabled. |
| loadingRows | number |  | How many skeleton rows to draw while loading. Default: the page size, at most 8. |
| mobileLayout | "table" \| "cards" | "table" | `cards` shows every row as a card while the table is narrower than 640 px: the first column is the title, the other columns are label and value. Text fields share a row three by three and truncate; fields that draw more than text (icons, controls, badges, avatars, charts) take the whole row and wrap. The expand toggle sits in the card and the footer becomes a summary under the cards. Default `table`. |
| onColumnFiltersChange | (next: ColumnFiltersState) => void |  | Called with the next column filters. |
| onColumnPinningChange | (next: ColumnPinningState) => void |  | Called with the next pinning state. |
| onColumnVisibilityChange | (next: ColumnVisibilityState) => void |  | Called with the next visibility state. |
| onExpandedChange | (next: ExpandedState) => void |  | Called with the next expanded state. |
| onExport | (context: DataTableExportContext<TData>) => void |  | Called instead of the file download. It gets the scope (`selected`, `all` or `page`), the rows, the CSV text and the file name. |
| onGlobalFilterChange | (next: string) => void |  | Called with the next search text. |
| onPaginationChange | (next: PaginationState) => void |  | Called with the next page and page size. |
| onQueryChange | (query: DataTableQuery) => void |  | Called when the page, the order, a filter or the search changes, and not on mount. It is the one callback to fetch from. |
| onRetry | () => void |  | Called by Try again in the error state. Without it the error has no button. |
| onRowSelectionChange | (next: RowSelectionState) => void |  | Called with the next selection, an object of selected row ids. |
| onSortingChange | (next: SortingState) => void |  | Called with the next sorting. |
| pageSizeOptions | number[] | DEFAULT_PAGE_SIZES | The choices in Rows per page. Default `[10, 20, 50]`; the current page size is added when it is not listed. |
| paginated | boolean | true | Shows the footer pager. `false` shows every row at once. Default `true`. |
| pagination | PaginationState |  | The page and page size as TanStack state: `{ pageIndex: 0, pageSize: 10 }`. Pass it with `onPaginationChange` to control it. |
| pinnable | boolean | true | Shows Pin to start and Pin to end in the column menus. Default `true`. |
| renderSubRow | (row: TData) => React.ReactNode |  | Draws a panel under a row when its chevron is opened. Passing it adds the expander column. The panel is as wide as the visible part of the table and sticks to its start edge while a wide table scrolls. |
| resizableColumns | boolean | false | A handle on the edge of every header cell. Drag it, or focus it and use the arrow keys; double-click resets the column. The minimum is 80 px. Default `false`. |
| rowCount | number |  | The total number of rows on the server. Needed for the page count when the server pages. |
| rowLabel | (row: TData) => string |  | Names a row for assistive technology: the checkbox reads `Select INV-2001` instead of `Select row 1`. |
| rowNumbers | boolean | false | A narrow first column with the row's position, 1 to n, in the current order and across pages. Default: off. |
| rowSelection | RowSelectionState |  | The selected rows as an object of ids. Pass it with `onRowSelectionChange` to control it. |
| searchable | boolean | true | Shows the search field. Default `true`. |
| searchPlaceholder | string | "Search…" | The placeholder of the search field. Default `Search…`. |
| selectable | boolean | true | Row checkboxes, shift-click ranges and the floating action bar. Default `true`. |
| serverSide | DataTableServerSide |  | Hands paging, sorting and filtering to your API. `true` means all three; an object picks `pagination`, `sorting` or `filtering`. `data` is then one page. |
| showRowCount | boolean | true | The "n rows" (or "n of m rows selected") line under the table. Set to false when the footer row or the page says it already; without pagination the bar under the table is then left out. Default: true. |
| sorting | SortingState |  | The sort order as TanStack state: `[{ id: "amount", desc: true }]`. Pass it with `onSortingChange` to control it. |
| toolbarActions | React.ReactNode |  | Extra buttons at the right end of the toolbar. |

### DataGrid

| Prop | Type | Default | Description |
|---|---|---|---|
| columns* | DataGridColumn<T>[] |  |  |
| data* | T[] |  |  |
| className | string |  |  |
| pageSize | number | 5 | Rows per page. Default 5. |
| searchable | boolean | true | Search field above the grid (uses each column's filterValue). Default true. |
| selectable | boolean | true | Row checkboxes and the "n of m selected" footer. Default true; false shows the row count instead. |

## Examples

### Filters: text, select, multi-select and number range

### Sorting: one column or several

### Selection: some rows, a page, every row

### Columns: hidden or pinned

### Data source: in the browser or from a server

### States: ready, loading, empty, no results and error

### URL state: the view in the address bar

### Simple table: search, selection and pages

### Editable cells: select, switch, slider and colour

### Cards on small screens

### Calculations: a footer per column, row numbers and header icons

## In context

### Invoices: archive rows and undo

A page with a heading, a call to action and the table. Archive removes the selected rows, a status line says how many went, and Undo puts them back in place.

### Orders from an API: loading, filters and a failed request

Every page, order, filter and search is a request, so the table shows skeleton rows while it waits. Turn on Simulate an outage and the next request fails, then Try again asks once more.

### Team members: a pinned name and detail rows

The name stays in view while other columns scroll, a row opens to show what does not fit in a cell, and the toolbar holds the page's one call to action. Export writes the visible columns only.

### Export: the CSV goes to your code

Export and Export selected download a file by default. With an export handler the table hands your code the CSV text, rows and file name instead, to send to an API or open a dialog.

### Density, a formatted total and no row count

`density` sets the row padding only: compact 4 px, default 6 px, relaxed 14 px. The footer writes a sum with the column's `meta.footerFormat`, and a narrow column grows to fit its total, so nothing is cut. `showRowCount={false}` leaves out the "n rows" line when the footer row already sums up. An empty footer cell of a narrow column shows only the + of Calculate.

## For AI agents

`get_component("data-table")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
