DataTable
The table every app needs: search, filter chips, multi-column sorting, pagination, selection with bulk actions, column controls, row links and details, inline editing and CSV export, in client or server mode.
Status: stable. Category: Patterns.
import { DataTable } from '@glyphui/ui/data-table'
Exports: DataTable, dataTableStyles, filterChipStyles, createColumnHelper, useTableUrlState, getFilterList, parseTableSearch, tableSearch, writeTableSearch, historyAdapter, editableCell, exportTableCsv, toCsv.
Notes
- URL state format: page (1-based) and size, sort=column or column.desc (comma-separated for several), q for search, one f.<column> parameter per filter value (f.status=open&f.status=pending), and hide=col,col. Build links with tableSearch(state); a prefix keeps several tables apart.
- Columns are typed from your row type via createColumnHelper<T>(). Set meta: { align: "right" } on numeric columns.
- Requires @tanstack/react-table version 8 as a peer dependency (install @tanstack/react-table@8; version 9 is not supported yet).
- Pass columns to useTableUrlState so filters decode by type: a shared link with one status still gives a multi filter an array. In server code, getFilterList(state.columnFilters, "status") always returns an array.
- Every piece of state (page, sort, search, filters, visibility, sizes, pinning, order, selection, expanded rows, density) can be controlled through state and onStateChange, or left to the table. Pass getRowId so selections survive paging and data changes.
- Server mode: pass the current page as data, the total as rowCount (or hasNextPage for cursor APIs), and keep loading true while fetching. With TanStack Query, use placeholderData: keepPreviousData so the old page stays until the new one arrives.
- Select-all across pages sets allMatchingSelected in state; in server mode act on the query rather than the row ids.
- Clicks on buttons, links, checkboxes and menus inside a clickable row act on themselves. getRowHref renders the first column as a real link, so keyboard and middle-click work.
- CSV exports quote fields as RFC 4180 requires and prefix text starting with =, +, - or @ so spreadsheets don’t run it as a formula.
- For 10,000+ rows, pass virtualize from @glyphui/ui/data-table/virtual.
DataTable props
| Prop | Type | Default | Description |
|---|---|---|---|
columns (required) | ColumnDef<T, any>[] | Build with createColumnHelper<T>() for typed accessors. | |
data (required) | T[] | undefined | ||
aria-label | string | ||
bulkActions | ((selection: TableSelection<T>) => ReactNode) | Actions for the selected rows, in a floating bar while any are selected. | |
className | string | ||
columnControls | boolean | Partial<ColumnControls> | Column features: true turns on hiding (a View menu and each column's menu), resizing, pinning and reordering; or pick some. | |
defaultState | Partial<DataTableState> | Starting values for slices you don't control. | |
density | "default" | "compact" | "comfortable" | ||
densityToggle | boolean | Adds compact / default / comfortable to the View menu. | |
empty | ReactNode | Shown when there are no rows at all (not when a search matches nothing). | |
error | unknown | Shows an error state with a retry button when onRetry is set. | |
exportCsv | boolean | { fileName?: string; bom?: boolean; fetchAll?: (() => T[] | Promise<T[]>) | undefined; } | undefined | Adds an Export menu: this page, selected rows or all rows as CSV. In server mode pass fetchAll so "All rows" can load every page. | |
getRowCanExpand | ((row: T) => boolean) | ||
getRowCanSelect | ((row: T) => boolean) | Rows this returns false for get a disabled checkbox. | |
getRowHref | ((row: T) => string) | Makes each row a link: the first data column links there and the row is clickable. | |
getRowId | ((row: T, index: number) => string) | Stable row ids. Needed to keep selections across pages and data changes. | |
hasNextPage | boolean | Cursor paging (APIs without totals): whether a next page exists. | |
initialSorting | SortingState | ||
loading | boolean | Shows skeleton rows. In server mode the current rows stay, under a progress bar. | |
maxHeight | string | number | Scrolls inside the table past this height, with the header pinned. | |
mobile | "scroll" | "cards" | Below the sm breakpoint: scroll sideways (default) or show each row as a card. | |
mode | "client" | "server" | client (default) sorts, filters and pages data in the browser. server hands every change to you through onStateChange: pass the current page as data and the total as rowCount. | |
onCellEdit | ((edit: CellEdit<T>) => unknown) | Saves edits from editableCell() columns. Reject to roll the cell back. | |
onColumnFiltersChange | ((filters: ColumnFiltersState) => void) | ||
onLoadMore | (() => void) | Shows "Load more" instead of pages; append rows to data when it's called. | |
onPaginationChange | ((pagination: PaginationState) => void) | ||
onRetry | (() => unknown) | ||
onRowClick | ((row: T, event: MouseEvent<HTMLElement, MouseEvent>) => void) | Makes rows clickable. Clicks on buttons, links and checkboxes inside are left alone. | |
onSearchChange | ((search: string) => void) | ||
onSelectionChange | ((rows: T[]) => void) | ||
onSortingChange | ((sorting: SortingState) => void) | ||
onStateChange | ((state: DataTableState, changed: keyof DataTableState) => void) | Called with the whole next state, and the slice that changed, on every change. | |
pageSize | number | false | Rows per page, or false to show every row. Default 10. | |
pageSizeOptions | readonly number[] | Choices in "Rows per page". Default 10, 20, 50, 100. | |
renderSubRow | ((row: T) => ReactNode) | Adds an expand button to each row; this content opens below it. | |
rowCount | number | Server mode: rows across all pages. Omit it and pass hasNextPage for cursor paging. | |
search | boolean | { placeholder?: string; } | Adds a search box. In client mode it matches every column. | |
selectable | boolean | Adds a checkbox column. | |
state | Partial<DataTableState> | Controlled state: any slice you pass is yours to update from onStateChange. | |
toolbar | ReactNode | Extra controls at the end of the toolbar. | |
variant | "card" | "plain" | ||
virtualize | DataTableVirtualizer | Renders only rows in view. Create with virtualRows() from @glyphui/ui/data-table/virtual. |
Example: Sorting, search and selection
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
interface Invoice {
id: string
customer: string
status: 'paid' | 'open' | 'overdue'
total: number
}
const invoices: Invoice[] = [
{ id: 'INV-1042', customer: 'Northwind', status: 'paid', total: 1240 },
{ id: 'INV-1043', customer: 'Globex', status: 'open', total: 86.5 },
{ id: 'INV-1044', customer: 'Initech', status: 'overdue', total: 12900.75 },
{ id: 'INV-1045', customer: 'Umbrella', status: 'paid', total: 410 },
{ id: 'INV-1046', customer: 'Hooli', status: 'open', total: 2380 },
]
const tone = { paid: 'success', open: 'info', overdue: 'danger' } as const
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', {
header: 'Invoice',
cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
}),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={tone[info.getValue()]} dot>
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
search={{ placeholder: 'Search invoices…' }}
selectable
pageSize={4}
/>
)
}
Example: Filter chips
Declare meta.filter on a column: select, multi (with counts), range, date range or text. Shift-click headers to sort by more than one column.
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusOptions, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000)
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', {
header: 'Customer',
meta: { filter: { type: 'text', placeholder: 'Company name' } },
}),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
// Faceted counts appear beside each option, from the other active filters.
meta: { filter: { type: 'multi', options: statusOptions } },
}),
col.accessor('plan', {
header: 'Plan',
meta: {
filter: {
type: 'select',
options: [
{ value: 'Starter', label: 'Starter' },
{ value: 'Growth', label: 'Growth' },
{ value: 'Enterprise', label: 'Enterprise' },
],
},
},
}),
col.accessor('issued', {
header: 'Issued',
cell: (info) => formatDay(info.getValue()),
meta: {
filter: {
type: 'date-range',
presets: [
{ label: 'Last 7 days', range: () => ({ from: daysAgo(6), to: new Date() }) },
{ label: 'Last 30 days', range: () => ({ from: daysAgo(29), to: new Date() }) },
],
},
},
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: {
align: 'right',
filter: { type: 'range', min: 0, step: 100, format: (n) => usd.format(n) },
},
}),
]
export default function Example() {
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={8}
defaultState={{ columnFilters: [{ id: 'status', value: ['open', 'overdue'] }] }}
/>
)
}
Example: Server mode
mode="server" hands paging, sorting, search and filters to your API through onStateChange. Rows stay on screen while the next page loads.
import { Badge, Button, toast } from '@glyphui/ui'
import {
createColumnHelper,
DataTable,
type DataTableState,
getFilterList,
} from '@glyphui/ui/data-table'
import { Archive } from 'lucide-react'
import { useEffect, useState } from 'react'
import { fetchInvoices, formatDay, type Invoice, statusOptions, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
export default function Example() {
const [query, setQuery] = useState<
Pick<DataTableState, 'pagination' | 'sorting' | 'search' | 'columnFilters'>
>({
pagination: { pageIndex: 0, pageSize: 10 },
sorting: [{ id: 'issued', desc: true }],
search: '',
columnFilters: [],
})
const [result, setResult] = useState<Awaited<ReturnType<typeof fetchInvoices>>>()
const [loading, setLoading] = useState(true)
useEffect(() => {
let current = true
setLoading(true)
// Always an array, even when a shared link held a single status.
const statuses = getFilterList(query.columnFilters, 'status')
fetchInvoices({
page: query.pagination.pageIndex,
pageSize: query.pagination.pageSize,
sort: query.sorting[0],
search: query.search,
...(statuses.length > 0 && { statuses }),
}).then((next) => {
if (!current) return
setResult(next)
setLoading(false)
})
return () => {
current = false
}
}, [query])
const columns = [
col.accessor('id', {
header: 'Invoice',
cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
}),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
enableSorting: false,
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
meta: {
// The server sends counts, so the filter shows them without loading every row.
filter: {
type: 'multi',
options: statusOptions.map((o) => ({ ...o, count: result?.statusCounts[o.value] ?? 0 })),
},
},
}),
col.accessor('issued', { header: 'Issued', cell: (info) => formatDay(info.getValue()) }),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
return (
<DataTable
aria-label="Invoices"
mode="server"
data={result?.rows}
rowCount={result?.total}
loading={loading}
columns={columns}
getRowId={(row) => row.id}
state={query}
onStateChange={(next) =>
setQuery({
pagination: next.pagination,
sorting: next.sorting,
search: next.search,
columnFilters: next.columnFilters,
})
}
search={{ placeholder: 'Search 312 invoices…' }}
selectable
bulkActions={(selection) => (
<Button
size="sm"
variant="outline"
leftIcon={<Archive />}
onClick={() => {
toast.success(`Archived ${selection.count} invoices`)
selection.clear()
}}
>
Archive
</Button>
)}
/>
)
}
Example: State in the URL
useTableUrlState keeps the view shareable and the back button working, with any router.
import { Badge, Button } from '@glyphui/ui'
import { createColumnHelper, DataTable, useTableUrlState } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusOptions, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
meta: { filter: { type: 'multi', options: statusOptions } },
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
// Page, sort, search, filters and hidden columns live in the URL as `orders.*` params.
const url = useTableUrlState({ prefix: 'orders', pageSize: 5 })
return (
<DataTable
aria-label="Orders"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={5}
search={{ placeholder: 'Search orders…' }}
columnControls={{ hide: true }}
toolbar={
<Button variant="ghost" size="sm" onClick={url.reset}>
Reset view
</Button>
}
{...url}
/>
)
}
Example: Row actions and bulk actions
Select rows (or every matching row) and act on them from the floating bar.
import {
Badge,
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
IconButton,
toast,
useConfirm,
} from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { Copy, MoreHorizontal, Send, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { type Invoice, invoices as seed, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
export default function Example() {
const [rows, setRows] = useState(seed)
const confirm = useConfirm()
async function remove(ids: string[]) {
const ok = await confirm({
title: ids.length === 1 ? `Delete ${ids[0]}?` : `Delete ${ids.length} invoices?`,
description: 'Customers keep any PDFs already sent.',
tone: 'danger',
})
if (!ok) return false
setRows((current) => current.filter((row) => !ids.includes(row.id)))
toast.success(ids.length === 1 ? 'Invoice deleted' : `${ids.length} invoices deleted`)
return true
}
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
col.display({
id: 'actions',
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
icon={<MoreHorizontal />}
aria-label={`Actions for ${row.original.id}`}
size="sm"
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
icon={<Send />}
onSelect={() => toast.success(`Reminder sent to ${row.original.email}`)}
>
Send reminder
</DropdownMenuItem>
<DropdownMenuItem
icon={<Copy />}
onSelect={() => navigator.clipboard?.writeText(row.original.id)}
>
Copy ID
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
icon={<Trash2 />}
tone="danger"
onSelect={() => remove([row.original.id])}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
meta: { align: 'right', className: 'w-12' },
}),
]
return (
<DataTable
aria-label="Invoices"
data={rows}
columns={columns}
getRowId={(row) => row.id}
pageSize={8}
selectable
exportCsv={{ fileName: 'invoices.csv' }}
bulkActions={(selection) => (
<>
<Button
size="sm"
variant="outline"
leftIcon={<Send />}
onClick={() => toast.success(`Sent ${selection.count} reminders`)}
>
Remind
</Button>
<Button
size="sm"
variant="danger"
leftIcon={<Trash2 />}
onClick={async () => {
if (await remove(selection.ids)) selection.clear()
}}
>
Delete
</Button>
</>
)}
/>
)
}
Example: Column controls and density
Hide, resize, pin and reorder columns; pinned columns stay put while the table scrolls sideways.
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', {
header: 'Invoice',
size: 150,
cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
}),
col.accessor('customer', { header: 'Customer', size: 180 }),
col.accessor('email', { header: 'Billing email', size: 240 }),
col.accessor('plan', { header: 'Plan', size: 120 }),
col.accessor('status', {
header: 'Status',
size: 120,
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('issued', {
header: 'Issued',
size: 120,
cell: (info) => formatDay(info.getValue()),
}),
col.accessor('total', {
header: 'Total',
size: 130,
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={20}
// Hide, resize, pin and reorder from each column's ⋯ menu; drag headers to reorder.
columnControls
densityToggle
maxHeight={380}
defaultState={{ columnPinning: { left: ['id'] }, density: 'compact' }}
/>
)
}
Example: Clickable rows
Open details from a row.
import {
Badge,
DescriptionItem,
DescriptionList,
Sheet,
SheetBody,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { useState } from 'react'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
const [open, setOpen] = useState<Invoice | null>(null)
return (
<>
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={5}
selectable
// Click a row (or focus it and press Enter). Checkboxes and buttons keep their own clicks.
onRowClick={(row) => setOpen(row)}
/>
<Sheet open={open !== null} onOpenChange={(next) => !next && setOpen(null)}>
<SheetContent>
{open && (
<>
<SheetHeader>
<SheetTitle>{open.id}</SheetTitle>
<SheetDescription>{open.customer}</SheetDescription>
</SheetHeader>
<SheetBody>
<DescriptionList>
<DescriptionItem term="Status">{open.status}</DescriptionItem>
<DescriptionItem term="Total">{usd.format(open.total)}</DescriptionItem>
<DescriptionItem term="Issued">{formatDay(open.issued)}</DescriptionItem>
<DescriptionItem term="Billing email">{open.email}</DescriptionItem>
</DescriptionList>
</SheetBody>
</>
)}
</SheetContent>
</Sheet>
</>
)
}
Example: Expandable rows
import { Badge, DescriptionItem, DescriptionList } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
return (
<DataTable
aria-label="Invoices"
data={invoices.slice(0, 6)}
columns={columns}
getRowId={(row) => row.id}
pageSize={false}
// Drafts have nothing to show yet.
getRowCanExpand={(row) => row.status !== 'draft'}
renderSubRow={(row) => (
<DescriptionList className="grid-cols-2 gap-x-10 px-14 py-4 sm:grid-cols-4">
<DescriptionItem term="Billing email">{row.email}</DescriptionItem>
<DescriptionItem term="Plan">{row.plan}</DescriptionItem>
<DescriptionItem term="Issued">{formatDay(row.issued)}</DescriptionItem>
<DescriptionItem term="Tax (20%)">{usd.format(row.total * 0.2)}</DescriptionItem>
</DescriptionList>
)}
/>
)
}
Example: Inline editing
editableCell() edits in place. The new value shows at once and rolls back if saving fails: try more than 50 seats.
import { toast } from '@glyphui/ui'
import { createColumnHelper, DataTable, editableCell } from '@glyphui/ui/data-table'
import { useState } from 'react'
interface Seat {
id: string
name: string
role: 'admin' | 'member' | 'billing'
seats: number
}
const roles = [
{ value: 'admin', label: 'Admin' },
{ value: 'member', label: 'Member' },
{ value: 'billing', label: 'Billing' },
]
const col = createColumnHelper<Seat>()
const columns = [
col.accessor('name', {
header: 'Team',
cell: editableCell<Seat, string>({
validate: (value) => (value.trim().length < 2 ? 'Use at least 2 characters' : null),
}),
}),
col.accessor('role', {
header: 'Default role',
cell: editableCell<Seat, string>({ type: 'select', options: roles }),
}),
col.accessor('seats', {
header: 'Seats',
cell: editableCell<Seat, number>({
type: 'number',
validate: (value) => (value === null || value < 1 ? 'At least 1 seat' : null),
}),
meta: { align: 'right' },
}),
]
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
export default function Example() {
const [rows, setRows] = useState<Seat[]>([
{ id: 't1', name: 'Design', role: 'member', seats: 8 },
{ id: 't2', name: 'Engineering', role: 'member', seats: 24 },
{ id: 't3', name: 'Finance', role: 'billing', seats: 3 },
])
return (
<DataTable
aria-label="Teams"
data={rows}
columns={columns}
getRowId={(row) => row.id}
pageSize={false}
onCellEdit={async ({ rowId, columnId, value }) => {
await wait(500)
// The server refuses more than 50 seats: the cell rolls back and explains why.
if (columnId === 'seats' && Number(value) > 50) {
toast.error('Plans include up to 50 seats per team')
throw new Error('Plans include up to 50 seats per team')
}
setRows((current) =>
current.map((row) => (row.id === rowId ? { ...row, [columnId]: value } : row)),
)
}}
/>
)
}
Example: CSV export
import { Button } from '@glyphui/ui'
import { createColumnHelper, DataTable, exportTableCsv } from '@glyphui/ui/data-table'
import { Download } from 'lucide-react'
import { type Invoice, invoices, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('email', { header: 'Billing email' }),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
// Spreadsheets want plain numbers, not "$1,240.00".
meta: { align: 'right', csv: (value) => value.toFixed(2) },
}),
]
export default function Example() {
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={5}
selectable
// This page, selected rows, or every row that matches the search.
exportCsv={{ fileName: 'invoices.csv' }}
search
toolbar={
<Button
variant="ghost"
size="sm"
leftIcon={<Download />}
// Export without a table, e.g. after fetching everything from your API.
onClick={() => exportTableCsv({ data: invoices, columns, fileName: 'all-invoices.csv' })}
>
All, without the table
</Button>
}
/>
)
}
Example: Cards on small screens
mobile="cards" turns each row into a card below 640px.
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusTone, usd } from '../data'
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('customer', { header: 'Customer' }),
col.accessor('id', { header: 'Invoice' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
// Kept out of the cards to save space.
col.accessor('email', { header: 'Billing email', meta: { mobile: 'hidden' } }),
]
export default function Example() {
// Narrow your window below 640px: each row becomes a card, the first column leads it.
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
pageSize={4}
selectable
mobile="cards"
/>
)
}
Example: Loading and error
import { SegmentedControl } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { useState } from 'react'
interface Deploy {
id: string
branch: string
}
const col = createColumnHelper<Deploy>()
const columns = [
col.accessor('id', { header: 'Deploy' }),
col.accessor('branch', { header: 'Branch' }),
]
export default function Example() {
const [state, setState] = useState<'loading' | 'error' | 'empty'>('loading')
return (
<div className="grid gap-3">
<SegmentedControl
aria-label="State"
size="sm"
value={state}
onValueChange={setState}
options={[
{ value: 'loading', label: 'Loading' },
{ value: 'error', label: 'Error' },
{ value: 'empty', label: 'Empty' },
]}
/>
<DataTable
aria-label="Deploys"
data={state === 'empty' ? [] : undefined}
columns={columns}
loading={state === 'loading'}
error={state === 'error' ? new Error('Could not reach the deploy service.') : undefined}
onRetry={() => setState('empty')}
/>
</div>
)
}
Example: Theme recipe
Set variant, density and slot classes for every DataTable from the theme file.
import { Badge, defineTheme, presets, ThemeScope } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusTone, usd } from '../data'
// In your theme file: every DataTable becomes compact and borderless, with a tinted header.
const theme = defineTheme({
name: 'ledger',
extends: presets.glyph,
components: {
DataTable: {
defaultVariants: { variant: 'plain', density: 'compact' },
className: {
head: 'bg-subtle text-[0.6875rem] tracking-wide [&_button]:uppercase',
row: 'odd:bg-subtle/40',
},
},
},
})
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={statusTone[info.getValue()]} className="capitalize">
{info.getValue()}
</Badge>
),
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export default function Example() {
return (
<ThemeScope theme={theme} className="w-full bg-transparent">
<DataTable aria-label="Invoices" data={invoices} columns={columns} pageSize={6} />
</ThemeScope>
)
}
Live page: https://glyphui.xyz/components/data-table