Data tables
Sorting, filters, server mode, URL state, bulk actions and virtualization.
DataTable from @glyphui/ui/data-table is the table most apps end up building by hand: search, filter chips, multi-column sorting, pagination, selection with bulk actions, column controls, clickable and expandable rows, inline editing and CSV export, with loading, empty and error states. It runs on TanStack Table version 8.
npm install @tanstack/react-table@8
Columns and rows
Columns are typed from your row type with createColumnHelper. getRowId keeps selections stable across pages and data changes.
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 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' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('status', {
header: 'Status',
cell: (info) => (
<Badge tone={tone[info.getValue()]} dot className="capitalize">
{info.getValue()}
</Badge>
),
meta: {
filter: {
type: 'multi',
options: [
{ value: 'paid', label: 'Paid' },
{ value: 'open', label: 'Open' },
{ value: 'overdue', label: 'Overdue' },
],
},
},
}),
col.accessor('total', {
header: 'Total',
cell: (info) => usd.format(info.getValue()),
meta: { align: 'right' },
}),
]
export function InvoicesTable({ invoices }: { invoices: Invoice[] }) {
return (
<DataTable
aria-label="Invoices"
data={invoices}
columns={columns}
getRowId={(row) => row.id}
search={{ placeholder: 'Search invoices…' }}
selectable
columnControls
/>
)
}
Define columns outside the component (or memoize them) so the table doesn't rebuild on every render. Set meta: { align: 'right' } on numeric columns.
Filters
meta.filter on a column adds it to the Filter menu, and active filters show as chips above the table. Types: select, multi (with match counts), range, date-range and text. Shift-click column headers to sort by several columns.
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'] }] }}
/>
)
}
Live example: https://glyphui.xyz/components/data-table
Server mode
With mode="server", the table hands paging, sorting, search and filters to you through onStateChange. Pass the current page as data, the total as rowCount, and loading while you fetch; the previous rows stay on screen under a progress bar until the new page arrives.
import {
createColumnHelper,
DataTable,
type DataTableState,
getFilterList,
} from '@glyphui/ui/data-table'
import { useEffect, useState } from 'react'
interface Invoice {
id: string
customer: string
total: number
}
interface Page {
rows: Invoice[]
total: number
}
const col = createColumnHelper<Invoice>()
const columns = [
col.accessor('id', { header: 'Invoice' }),
col.accessor('customer', { header: 'Customer' }),
col.accessor('total', { header: 'Total', meta: { align: 'right' } }),
]
type Query = Pick<DataTableState, 'pagination' | 'sorting' | 'search' | 'columnFilters'>
async function fetchInvoices(query: Query): Promise<Page> {
const params = new URLSearchParams({
page: String(query.pagination.pageIndex),
size: String(query.pagination.pageSize),
q: query.search,
})
for (const status of getFilterList(query.columnFilters, 'status')) params.append('status', status)
const sort = query.sorting[0]
if (sort) params.set('sort', `${sort.id}.${sort.desc ? 'desc' : 'asc'}`)
return (await fetch(`/api/invoices?${params}`)).json()
}
export function ServerInvoices() {
const [query, setQuery] = useState<Query>({
pagination: { pageIndex: 0, pageSize: 25 },
sorting: [],
search: '',
columnFilters: [],
})
const [page, setPage] = useState<Page>()
const [loading, setLoading] = useState(true)
useEffect(() => {
let current = true
setLoading(true)
fetchInvoices(query).then((next) => {
// Ignore responses that arrive after a newer query.
if (!current) return
setPage(next)
setLoading(false)
})
return () => {
current = false
}
}, [query])
return (
<DataTable
aria-label="Invoices"
mode="server"
data={page?.rows}
rowCount={page?.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
/>
)
}
getFilterList(state.columnFilters, 'status')always returns an array, even when a shared link held a single value.- APIs without a total pass
hasNextPagefor cursor paging, oronLoadMorefor a "Load more" list. - In
multifilters, give options acountfrom your server and the menu shows it.
With TanStack Query, keep the previous page while the next one loads:
const { data, isFetching } = useQuery({
queryKey: ['invoices', query],
queryFn: () => fetchInvoices(query),
placeholderData: keepPreviousData,
})
<DataTable mode="server" data={data?.rows} rowCount={data?.total} loading={isFetching} … />
State in the URL
useTableUrlState stores the page, sort, search, filters and hidden columns in the URL, so a view can be shared and the back button works. Spread what it returns onto the table:
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}
/>
)
}
Live example: https://glyphui.xyz/components/data-table
prefixkeeps several tables on one page apart (orders.page,orders.sort).- Pass
columnsso filters decode by type: a shared link with one status still gives amultifilter an array. - With React Router, pass
adapter: useRouterUrlAdapter()from@glyphui/ui/react-router.
The format is readable: page (from 1) and size, sort=column or column.desc (comma-separated for several), q for search, one f.<column> parameter per filter value, and hide=col,col. Build links to a view, for example from a command menu, with tableSearch:
import { tableSearch } from '@glyphui/ui/data-table'
// "?q=INV-1043&f.status=overdue"
export const overdueInvoice = `/invoices${tableSearch({
search: 'INV-1043',
columnFilters: [{ id: 'status', value: ['overdue'] }],
})}`
Selection and bulk actions
selectable adds checkboxes. Select every row on the page and a banner offers to select every matching row; bulkActions renders your actions in a 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>
</>
)}
/>
)
}
Live example: https://glyphui.xyz/components/data-table
In server mode, "select all" sets allMatchingSelected in the state instead of listing ids. Act on the query, not the ids, when it's set.
Rows
onRowClick(row)opens details, for example in a Sheet. Clicks on buttons, links, checkboxes and menus inside the row act on themselves.getRowHref(row)renders the first column as a real link, so keyboard users, middle-click and "open in new tab" work.renderSubRow(row)adds an expander with any content below the row.
Inline editing
editableCell() edits text, numbers or choices in place. onCellEdit saves: the new value shows at once and rolls back if your promise rejects.
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)),
)
}}
/>
)
}
Live example: https://glyphui.xyz/components/data-table
Export, density and columns
exportCsvadds an Export menu: this page, the selected rows, or every row (in server mode, passfetchAll). Fields are quoted per RFC 4180, and text that starts like a formula (=,+,-,@) is neutralized so spreadsheets don't run it.exportTableCsv()andtoCsv()export without a table.densityToggleadds compact, default and comfortable rows. A theme can set the default for every table.columnControlsadds hiding, drag and keyboard resizing, pinning and reordering.
Phones
mobile="cards" turns each row into a card below 640px, using the column headers as labels. The default scrolls the table sideways.
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"
/>
)
}
Live example: https://glyphui.xyz/components/data-table
Ten thousand rows
For large client-side tables, render only the visible rows with virtualRows from @glyphui/ui/data-table/virtual:
npm install @tanstack/react-virtual
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { virtualRows } from '@glyphui/ui/data-table/virtual'
interface LogEvent {
id: string
name: string
}
const col = createColumnHelper<LogEvent>()
const columns = [col.accessor('id', { header: 'ID' }), col.accessor('name', { header: 'Event' })]
// Create the virtualizer once, outside the component.
const virtual = virtualRows({ height: 480 })
export function AllEvents({ events }: { events: LogEvent[] }) {
return (
<DataTable
aria-label="Events"
data={events}
columns={columns}
getRowId={(row) => row.id}
pageSize={false}
virtualize={virtual}
/>
)
}
Search, sort and select still work across every row, and screen readers get the full row count. Expandable rows aren't virtualized; use pages for tables with row details.
Live page: https://glyphui.xyz/docs/data-tables