[!NOTE] Compound component — an opinionated composition of Helix primitives. Composes:
Table,Button,DropdownMenu.
Import
import {
TableColumnSettings,
TableColumnSettingsCell,
useColumnVisibility,
type TableColumnSettingsColumn,
} from "@timelycare/helix-ui"
Usage
const COLUMNS: TableColumnSettingsColumn[] = [
{ id: "name", label: "Name", locked: true },
{ id: "email", label: "Email" },
{ id: "group", label: "Group" },
{ id: "lastVisit", label: "Last visit" },
{ id: "status", label: "Status" },
]
const columns = useColumnVisibility({ lastVisit: false })
const shown = COLUMNS.filter((c) => columns.isVisible(c.id))
<Table>
<TableHeader>
<TableRow>
{shown.map((c) => <TableHead key={c.id}>{c.label}</TableHead>)}
<TableColumnSettings
columns={COLUMNS}
visibility={columns.visibility}
onVisibilityChange={columns.setVisibility}
defaultVisibility={columns.defaultVisibility}
/>
</TableRow>
</TableHeader>
<TableBody>
{members.map((m) => (
<TableRow key={m.id}>
{shown.map((c) => <TableCell key={c.id}>{m[c.id]}</TableCell>)}
<TableColumnSettingsCell>
<RowActionsMenu member={m} />
</TableColumnSettingsCell>
</TableRow>
))}
</TableBody>
</Table>
Where the gear goes
The gear is the last cell of the header row, right-aligned. TableColumnSettings renders that cell itself, so the gear cannot end up anywhere else.
- Rows with actions: put each row's kebab in its
TableColumnSettingsCell. The gear sits directly above the row menus, and all of the table's controls line up in one column. - Rows without actions: leave
TableColumnSettingsCellempty. The table gets a narrow last column that holds only the gear. - Never on its own row above the table, and never in the toolbar. Teams that put the gear in the corner of a card above the table should move it into the header.
The pinned column
The gear's column stays pinned to the right edge of the table when it scrolls sideways, so the gear and the row menus are always in reach. It works with stickyHeader: the corner cell stays put on both axes.
The pinned cells handle the details themselves. In a card table they cover the card's right padding, so no column shows beside them while the table is scrolled. They take the row's hover, selected and striped background, and they redraw the row's keyboard focus ring. Don't add your own background, z-index or stopPropagation to them.
Which columns can be hidden
The menu lists columns in the order given, under the label "Columns". Ticking or unticking a column applies at once, and the menu stays open so several can be changed in one visit.
- Mark the column that names the row
locked: true. It stays in the menu, ticked and disabled. If your state has hidden it anyway, it shows unticked and can be ticked again. - The last visible column can't be unticked, so the table never empties.
- Hiding a column is yours to render: draw its
TableHeadandTableCellonly whenisVisible(id)is true. A full-width empty-state cell spans the visible columns plus one, for the gear's column.
Saving people's choices
TableColumnSettings reports every change through onVisibilityChange, as the whole next map, and keeps nothing itself. Save the choice wherever the app keeps preferences, and pass it back as useColumnVisibility's second argument:
import { useState } from "react"
import { useColumnVisibility, type ColumnVisibility } from "@timelycare/helix-ui"
const KEY = "members-table-columns"
const DEFAULT_COLUMNS: ColumnVisibility = { lastVisit: false }
function readSaved(): ColumnVisibility | undefined {
try {
return JSON.parse(localStorage.getItem(KEY) ?? "null") ?? undefined
} catch {
return undefined // no storage, or a bad value
}
}
export function useSavedColumns() {
const [saved] = useState(readSaved)
const columns = useColumnVisibility(DEFAULT_COLUMNS, { ...DEFAULT_COLUMNS, ...saved })
// Pass this to <TableColumnSettings onVisibilityChange={...} />.
function onVisibilityChange(next: ColumnVisibility) {
columns.setVisibility(next)
try {
localStorage.setItem(KEY, JSON.stringify(next))
} catch {} // storage full or blocked: the choice still applies this visit
}
return { ...columns, onVisibilityChange }
}
Use it in place of useColumnVisibility, and pass columns.onVisibilityChange to TableColumnSettings instead of columns.setVisibility.
- Save in
onVisibilityChange, not in an effect on mount. An effect also runs on mount and would write the default over a saved choice that has not loaded yet. - Spread the default under the saved map, so a map that lacks a key still inherits the default's hidden columns.
initialVisibilityis read once, on mount. If the saved choice arrives later, mount the table after it loads, give it akeythat changes with it, or callsetVisibility(saved)when it arrives.- Server rendering has no
localStorage. On a server-rendered page, read the saved choice after mount, or render the table on the client only. Otherwise the server's default and the client's saved choice disagree on the first render.
The first argument stays the table's default, which is what "Reset columns" returns to. Called with no defaults, useColumnVisibility() returns defaultVisibility: {} (every column visible), so Reset shows every column; omit the defaultVisibility prop for no Reset item.
Resetting
Pass defaultVisibility and the menu ends with Reset columns. It is disabled while every column already matches the default, and it closes the menu when used. Without defaultVisibility there is no reset item.
With TanStack Table
ColumnVisibility has TanStack Table's VisibilityState shape, so the visibility state fits. The column defs and cells do not plug in as they are:
- Pass only the columns that have a label.
getAllLeafColumns()also holds internal columns, such as a selection checkbox. - The kebab stays out of the TanStack column defs. Put it in
TableColumnSettingsCell, afterrow.getVisibleCells(). TableColumnSettingsgoes afterheaderGroup.headers, as the last cell of the header row.
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
type VisibilityState,
} from "@tanstack/react-table"
import {
Table,
TableBody,
TableCell,
TableColumnSettings,
TableColumnSettingsCell,
TableHead,
TableHeader,
TableRow,
type TableColumnSettingsColumn,
} from "@timelycare/helix-ui"
interface Member {
id: string
name: string
email: string
group: string
}
const LABELS: Record<string, string> = { name: "Name", email: "Email", group: "Group" }
const DEFAULT_VISIBILITY: VisibilityState = { group: false }
const columnDefs: ColumnDef<Member>[] = [
{ id: "name", accessorKey: "name", header: LABELS.name, enableHiding: false },
{ id: "email", accessorKey: "email", header: LABELS.email },
{ id: "group", accessorKey: "group", header: LABELS.group },
]
export function MembersTable({ members }: { members: Member[] }) {
const table = useReactTable({
data: members,
columns: columnDefs,
getCoreRowModel: getCoreRowModel(),
initialState: { columnVisibility: DEFAULT_VISIBILITY },
})
const settingsColumns: TableColumnSettingsColumn[] = table
.getAllLeafColumns()
.filter((c) => c.id in LABELS)
.map((c) => ({ id: c.id, label: LABELS[c.id], locked: !c.getCanHide() }))
return (
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
<TableColumnSettings
columns={settingsColumns}
visibility={table.getState().columnVisibility}
onVisibilityChange={table.setColumnVisibility}
defaultVisibility={DEFAULT_VISIBILITY}
/>
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
{/* The row's kebab goes here when rows have actions. */}
<TableColumnSettingsCell />
</TableRow>
))}
</TableBody>
</Table>
)
}