Examples
Staged filtering and selection
Apply filters as one change, keep page selection explicit, and preserve the table while rows load.
Project directory
Fixture data only. Search and filter locally; this example makes no backend request.
Scroll horizontally to see all table columns.
Project data table with staged filters, sorting, visible-page selection, and request states
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import type { FormEvent } from "react";
import { AlertCircleIcon, CheckIcon, ChevronLeftIcon, ChevronRightIcon, SearchIcon } from "@phuctech/ui/icons";
import { Badge } from "@phuctech/ui/components/badge";
import { Button } from "@phuctech/ui/components/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@phuctech/ui/components/card";
import { Checkbox } from "@phuctech/ui/components/checkbox";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@phuctech/ui/components/dialog";
import { Input } from "@phuctech/ui/components/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@phuctech/ui/components/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@phuctech/ui/components/table";
type ProjectStatus = "Active" | "Paused" | "Invited";
type StatusFilter = "all" | ProjectStatus;
type LoadState = "ready" | "loading" | "error";
type SortKey = "name" | "owner" | "status" | "updated";
type SortDirection = "ascending" | "descending";
type ProjectRow = {
id: string;
name: string;
owner: string;
status: ProjectStatus;
updated: string;
updatedOrder: number;
};
const pageSize = 3;
const projects: readonly ProjectRow[] = [
{ id: "atlas", name: "Atlas onboarding", owner: "Mai Nguyen", status: "Active", updated: "8 min ago", updatedOrder: 5 },
{ id: "orbit", name: "Orbit billing", owner: "Phuc Tran", status: "Invited", updated: "Yesterday", updatedOrder: 4 },
{ id: "lumen", name: "Lumen research", owner: "Linh Do", status: "Paused", updated: "3 days ago", updatedOrder: 3 },
{ id: "nova", name: "Nova analytics", owner: "Quang Le", status: "Active", updated: "5 days ago", updatedOrder: 2 },
{ id: "sol", name: "Sol support", owner: "An Tran", status: "Invited", updated: "1 week ago", updatedOrder: 1 },
];
const sortableColumns: readonly (readonly [SortKey, string])[] = [
["name", "Project"],
["owner", "Owner"],
["status", "Status"],
["updated", "Updated"],
];
function statusVariant(status: ProjectStatus) {
if (status === "Active") return "success" as const;
if (status === "Paused") return "warning" as const;
return "info" as const;
}
function resultRange(page: number, total: number) {
if (total === 0) return "0 of 0";
const start = (page - 1) * pageSize + 1;
return `${start}–${Math.min(page * pageSize, total)} of ${total}`;
}
export function DataTablePattern() {
const [draftQuery, setDraftQuery] = useState("");
const [draftStatus, setDraftStatus] = useState<StatusFilter>("all");
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
const [selected, setSelected] = useState<string[]>([]);
const [page, setPage] = useState(1);
const [sortKey, setSortKey] = useState<SortKey>("name");
const [sortDirection, setSortDirection] = useState<SortDirection>("ascending");
const [loadState, setLoadState] = useState<LoadState>("ready");
const [notice, setNotice] = useState("");
const [archiveOpen, setArchiveOpen] = useState(false);
const retryTimerRef = useRef<number | null>(null);
useEffect(() => () => {
if (retryTimerRef.current !== null) {
window.clearTimeout(retryTimerRef.current);
}
}, []);
const filteredRows = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
return projects.filter((row) => {
const matchesQuery =
!normalizedQuery ||
`${row.name} ${row.owner}`.toLowerCase().includes(normalizedQuery);
const matchesStatus = statusFilter === "all" || row.status === statusFilter;
return matchesQuery && matchesStatus;
});
}, [query, statusFilter]);
const sortedRows = useMemo(() => {
return [...filteredRows].sort((left, right) => {
const comparison = sortKey === "updated"
? left.updatedOrder - right.updatedOrder
: left[sortKey].localeCompare(right[sortKey]);
return sortDirection === "ascending" ? comparison : -comparison;
});
}, [filteredRows, sortDirection, sortKey]);
const totalPages = Math.max(1, Math.ceil(sortedRows.length / pageSize));
const visibleRows = sortedRows.slice((page - 1) * pageSize, page * pageSize);
const allVisibleSelected =
visibleRows.length > 0 && visibleRows.every((row) => selected.includes(row.id));
const someVisibleSelected =
visibleRows.some((row) => selected.includes(row.id)) && !allVisibleSelected;
function clearRetryTimer() {
if (retryTimerRef.current !== null) {
window.clearTimeout(retryTimerRef.current);
retryTimerRef.current = null;
}
}
function applyFilters(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (loadState === "loading") return;
setQuery(draftQuery);
setStatusFilter(draftStatus);
setSelected([]);
setPage(1);
setNotice("");
}
function toggleRow(id: string) {
setSelected((current) =>
current.includes(id)
? current.filter((selectedId) => selectedId !== id)
: [...current, id],
);
}
function toggleVisibleRows() {
const visibleIds = visibleRows.map((row) => row.id);
setSelected((current) =>
allVisibleSelected
? current.filter((id) => !visibleIds.includes(id))
: Array.from(new Set([...current, ...visibleIds])),
);
}
function changePage(nextPage: number) {
setPage(Math.min(Math.max(nextPage, 1), totalPages));
setSelected([]);
}
function changeSort(nextKey: SortKey) {
if (sortKey === nextKey) {
setSortDirection((current) => current === "ascending" ? "descending" : "ascending");
} else {
setSortKey(nextKey);
setSortDirection("ascending");
}
setPage(1);
setSelected([]);
}
function simulateError() {
clearRetryTimer();
setNotice("");
setLoadState("error");
}
function retry() {
if (loadState !== "error") return;
clearRetryTimer();
setLoadState("loading");
retryTimerRef.current = window.setTimeout(() => {
retryTimerRef.current = null;
setLoadState("ready");
}, 500);
}
function archiveSelected() {
const count = selected.length;
setNotice(
`In this example, ${count} ${count === 1 ? "project is" : "projects are"} ready to archive. No data was changed.`,
);
setSelected([]);
setArchiveOpen(false);
}
return (
<Card className="w-full max-w-4xl">
<CardHeader className="gap-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<CardTitle>Project directory</CardTitle>
<CardDescription>Fixture data only. Search and filter locally; this example makes no backend request.</CardDescription>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={simulateError}
disabled={loadState === "loading"}
>
Simulate error
</Button>
</div>
<form
aria-label="Filter projects"
className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_12rem_auto]"
onSubmit={applyFilters}
>
<div className="relative">
<SearchIcon aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
aria-label="Search projects"
className="pl-9"
placeholder="Search name or owner"
value={draftQuery}
onChange={(event) => setDraftQuery(event.target.value)}
disabled={loadState === "loading"}
/>
</div>
<Select
value={draftStatus}
onValueChange={(value) => setDraftStatus((value ?? "all") as StatusFilter)}
disabled={loadState === "loading"}
>
<SelectTrigger aria-label="Filter by status">
<SelectValue>{draftStatus === "all" ? "All statuses" : draftStatus}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="Active">Active</SelectItem>
<SelectItem value="Paused">Paused</SelectItem>
<SelectItem value="Invited">Invited</SelectItem>
</SelectContent>
</Select>
<Button type="submit" disabled={loadState === "loading"}>
Apply filters
</Button>
</form>
</CardHeader>
<CardContent className="grid gap-3">
{selected.length > 0 ? (
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-primary/30 bg-primary/5 p-3">
<p className="flex-1 text-sm text-foreground" role="status">
{selected.length} selected
</p>
<Dialog open={archiveOpen} onOpenChange={setArchiveOpen}>
<DialogTrigger render={<Button type="button" size="sm"><CheckIcon aria-hidden="true" />Archive selected</Button>} />
<DialogContent>
<DialogHeader>
<DialogTitle>Archive selected projects?</DialogTitle>
<DialogDescription>
This example marks {selected.length} selected {selected.length === 1 ? "project" : "projects"} as ready to archive. No project data will be changed.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline">Cancel</Button>} />
<Button type="button" variant="destructive" onClick={archiveSelected}>
Archive selected
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
) : null}
{notice ? (
<p className="text-sm text-[color:var(--color-success-text)]" role="status">
{notice}
</p>
) : null}
{loadState === "error" ? (
<div className="grid gap-3 rounded-lg border border-[color:var(--color-danger-border)] bg-[color:var(--color-danger-bg)] p-6 text-center">
<AlertCircleIcon aria-hidden="true" className="mx-auto text-[color:var(--color-danger-text)]" />
<div role="alert">
<p className="font-medium text-foreground">The project list could not load.</p>
<p className="mt-1 text-sm text-muted-foreground">Your filter choices are saved in this example. Try again to restore the fixture rows.</p>
</div>
<Button type="button" variant="outline" className="mx-auto" onClick={retry}>
Try again
</Button>
</div>
) : (
<>
<p className="text-xs text-muted-foreground sm:hidden">Scroll horizontally to see all table columns.</p>
<div
role="region"
aria-label="Project table; scroll horizontally to see all columns"
aria-busy={loadState === "loading"}
tabIndex={0}
className="scrollbar-hover-reveal focus-ring overflow-x-auto rounded-lg border border-border"
>
<Table className="min-w-[42rem] text-left">
<caption className="sr-only">Projects, owners, statuses, and last update times</caption>
<TableHeader className="bg-muted/60">
<TableRow>
<TableHead className="w-12">
<Checkbox
aria-label="Select all visible projects"
checked={allVisibleSelected}
indeterminate={someVisibleSelected}
onCheckedChange={toggleVisibleRows}
disabled={loadState !== "ready" || visibleRows.length === 0}
/>
</TableHead>
{sortableColumns.map(([key, label]) => (
<TableHead key={key} aria-sort={sortKey === key ? sortDirection : "none"}>
<Button
type="button"
variant="ghost"
size="sm"
aria-label={`Sort by ${label}`}
className="h-8 px-1 text-xs"
onClick={() => changeSort(key)}
disabled={loadState !== "ready"}
>
{label}
<span aria-hidden="true">
{sortKey === key ? (sortDirection === "ascending" ? "↑" : "↓") : "↕"}
</span>
</Button>
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{loadState === "loading" ? (
<TableRow>
<TableCell colSpan={5} className="py-10 text-center text-muted-foreground" role="status">
Loading projects…
</TableCell>
</TableRow>
) : visibleRows.length > 0 ? (
visibleRows.map((row) => (
<TableRow key={row.id} selected={selected.includes(row.id)}>
<TableCell>
<Checkbox
aria-label={`Select ${row.name}`}
checked={selected.includes(row.id)}
onCheckedChange={() => toggleRow(row.id)}
/>
</TableCell>
<TableHead scope="row" className="h-auto px-3 py-2.5 text-sm font-medium text-foreground">
{row.name}
</TableHead>
<TableCell className="text-muted-foreground">{row.owner}</TableCell>
<TableCell><Badge variant={statusVariant(row.status)}>{row.status}</Badge></TableCell>
<TableCell className="text-muted-foreground">{row.updated}</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={5} className="py-10 text-center" role="status">
<p className="font-medium text-foreground">No matching projects</p>
<p className="mt-1 text-sm text-muted-foreground">Apply a different search or status filter.</p>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</>
)}
<div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
<span aria-live="polite" aria-atomic="true">{resultRange(page, filteredRows.length)}</span>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
aria-label="Previous page"
onClick={() => changePage(page - 1)}
disabled={page === 1 || loadState !== "ready"}
>
<ChevronLeftIcon aria-hidden="true" />
Previous
</Button>
<span>Page {page} of {totalPages}</span>
<Button
type="button"
variant="outline"
size="sm"
aria-label="Next page"
onClick={() => changePage(page + 1)}
disabled={page === totalPages || loadState !== "ready"}
>
Next
<ChevronRightIcon aria-hidden="true" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
}
When to use
Use this pattern when people compare rows, apply filters, and take actions on one or more records. It is a composition of the existing Card, Input, Select, Button, Checkbox, Badge, Dialog, and Table components, not a promise that column resizing, virtualization, or server-side pagination already exist.
Filters and requests
- Keep draft filter inputs local until the person activates Apply filters; do not request data on every keystroke for a staged form.
- When live search is truly the right interaction, debounce it and cancel or ignore stale requests.
- Fetch a list or a bulk detail endpoint once. Never fire one request per selected row or expanded row.
- Reset the page and selection when Apply filters changes the result set.
- Use a bounded horizontal scroll region for a wide table on a narrow screen; keep the page itself within the viewport.
Selection
Make the scope of a bulk action visible: show the selected count, keep the select-all checkbox scoped to the current page, and name the action with its consequence. If the action is destructive, add the shared Dialog confirmation before it runs. The example’s Archive action only records a local status message; it does not change fixture rows or call a service.
Sorting and pagination
Use a Button inside each sortable column heading, put the current sort direction on the column header with aria-sort, and use a clear accessible name for each sort action. Keep the page range and current page in text. Sort values by their meaning: the example’s relative update labels use a fixed chronological order instead of alphabetic comparison. The example sorts its fixture rows locally; a real screen should connect these controls to its actual data source and preserve the server’s pagination contract.
States
The preview uses fixture data, including its retry delay and archive confirmation. It does not send requests. The Preview and Code/Copy tabs read the same source file, src/components/design/examples/source/data-table-pattern.tsx, so the copied version includes the behavior being shown. This pattern has no property playground because it has no public pattern-level props to explore.
Accessibility
- Use a real
tablewith a caption, column headers, and row headers when the data is tabular. - Give selection controls names that include the row identity; label the page and filter controls independently.
- Expose the sort direction on the column header and keep sort actions as keyboard-accessible PhucTech Buttons.
- Keep pagination buttons keyboard reachable and expose the current page in text, not only through disabled arrows.
- Name and make the horizontally scrolling table region keyboard-focusable; show a short scroll hint on narrow screens.
- Allow horizontal scrolling for a wide table at small widths; do not shrink labels until they become ambiguous.
Do and don’t
Keep filter, selection, status, and pagination state explicit so the table can be tested one transition at a time.
Build a dense grid with divs that only looks like a table or make a bulk action silently affect rows on another page.
Related
- CRUD defines edit and destructive actions around table rows.
- Badge labels row status with readable text.
- Layout & Grid sets the responsive boundary for wide data surfaces.