DataTable
A table with sorting, row selection, pages, loading and empty states. For server data, control sort and page and give pageCount; the table then shows the rows as given. rowHref makes the whole row a link to the record (the first cell is the link; Ctrl-click opens a new tab), and the checkbox and buttons in the row still work. rowActions adds a “⋯” menu to each row. The first cell of a row with rowHref is font-medium. With cards, each row is a card below 768 px (and in the cards view of viewKey): the first cell is the title, the other cells show their header, and hideOnCard columns are left out. A row holds as many cards as fit, each at least 18rem wide, so a phone shows one card in a row; group headers and totals take the full row. A column's description is a muted second line under its value (null, undefined and "" show nothing); in the first column of a row with rowHref it comes after the link, and links in it stay clickable. A column's cardSlot changes how its cell sits on the card, on cards only (below 768 px and in the cards view; the table rows do not change), and not for the first column, which is the card title: "end" at the end of the title line, "meta" in one wrapped line under the title, "block" full width under the meta (long text); none of them shows the header, and a cell with no value shows nothing. cardDescription: "block" on the title column shows its description on the cards as a full-width block after the meta line, not under the title; the table view does not change. density="compact" is for dense lists: cell py-2, header row h-9, card rows p-3 with gap-y-1. The default empty state is EmptyState variant="plain". For reports, totals adds a total row at the foot, and groupBy puts the rows in groups (in the order they first appear; a sort works inside each group), each with a header row (groupHeader) and a subtotal row (groupTotals). With groupBy the table shows all rows, without pages. density="print" is for a printed report: small cells (text-xs, px-1 py-1), a header row h-8 with wrapping text, no scroll box (the table is as wide as the page), no cards and no sticky header; totals and group rows take the same small cells. The caller leaves out pages and row links in a print copy. viewKey adds a Table and Cards switch at the end of the toolbar row and keeps the choice in the browser for each list. Below 768 px the list shows cards and no switch. titleColumn names the column that holds the row link and is the card title, when the first column is a small value such as a level badge or a time; the row checkbox and the row menu take their names from it, unless rowLabel is set. rowLabel makes the row link an empty link with that name, so the title cell keeps its own content and its own links work (a log line with links in it). It also names the row checkbox and the row menu. cardTitle gives each card its own title, for example the order and the customer when the customer column is hidden on cards. The table view keeps the title cell.
import { DataTable } from "@percentsa/ui";Examples
| Status | ||||
|---|---|---|---|---|
| INV-1062 | Nakhla Foods | Overdue | 6,000 | |
| INV-1061 | Masar | Paid | 6,250 | |
| INV-1060 | Najm Logistics | Due | 6,500 | |
| INV-1059 | Bayt Coffee | Overdue | 6,750 | |
| INV-1058 | Wadi Tech | Paid | 7,000 |
Code
export function DataTableExample() {
const t = useT();
const [selected, setSelected] = useState<string[]>([]);
return (
<div className="grid w-full grid-cols-1 gap-3">
<DataTable
columns={useInvoiceColumns()}
rows={INVOICES}
getRowId={(r) => r.id}
caption={t("Invoices", "الفواتير")}
hideCaption
defaultSort={{ key: "id", direction: "desc" }}
selectable
selected={selected}
onSelectedChange={setSelected}
pageSize={5}
/>
{selected.length > 0 && (
<Button size="sm" variant="secondary" className="justify-self-start" onClick={() => setSelected([])}>
{t("Clear selection", "إلغاء التحديد")}
</Button>
)}
</div>
);
}
/** A list: each row opens its invoice, "⋯" holds the row actions, and below 768 px the rows are cards. */Code
export function DataTableListExample() {
const t = useT();
const done = (title: string) => () => toast({ title });
return (
<DataTable
className="w-full"
columns={useInvoiceColumns()}
rows={INVOICES}
getRowId={(r) => r.id}
caption={t("Invoices", "الفواتير")}
hideCaption
selectable
pageSize={5}
cards
rowHref={(r) => `#${r.id}`}
rowActions={(r) => [
{ label: t("Duplicate", "تكرار"), onSelect: done(t("Invoice duplicated", "كُرّرت الفاتورة")) },
{
label: t("Send a reminder", "إرسال تذكير"),
disabled: r.status === "paid",
description: r.status === "paid" ? t("This invoice is paid.", "هذه الفاتورة مدفوعة.") : undefined,
onSelect: done(t("Reminder sent", "أُرسل التذكير")),
},
"separator",
{ label: t("Delete", "حذف"), danger: true, onSelect: done(t("Invoice deleted", "حُذفت الفاتورة")) },
]}
/>
);
}
/** A report: the invoices grouped by status (sorted inside each group), a subtotal per group and a total row. */| Customer | Invoice | Total | Comment |
|---|---|---|---|
| Sara Al-Qahtani+966 55 123 4567 | INV-1042Simplified tax invoice | 1,850 | Deliver after 5 pm. Call before arriving. |
| Omar Al-Harbi+966 50 765 4321 | INV-1043Simplified tax invoice | 320 | |
| Lina Al-Otaibi+966 56 111 2233 | INV-1044Simplified tax invoice | 12,400 | Gift wrap. |
Code
export function DataTableDenseExample() {
const t = useT();
type Order = { id: string; number: string; name: string; phone: string; total: number; comment: string };
const rows: Order[] = [
{ id: "1", number: "INV-1042", name: t("Sara Al-Qahtani", "سارة القحطاني"), phone: "0551234567", total: 1850, comment: t("Deliver after 5 pm. Call before arriving.", "التسليم بعد الخامسة مساءً. الاتصال قبل الوصول.") },
{ id: "2", number: "INV-1043", name: t("Omar Al-Harbi", "عمر الحربي"), phone: "0507654321", total: 320, comment: "" },
{ id: "3", number: "INV-1044", name: t("Lina Al-Otaibi", "لينا العتيبي"), phone: "0561112233", total: 12400, comment: t("Gift wrap.", "تغليف هدية.") },
];
const columns: DataTableColumn<Order>[] = [
// The first cell is the row link; the description comes after it, and the phone stays a working link.
{ key: "name", header: t("Customer", "العميل"), description: (r) => <PhoneText value={r.phone} /> },
{ key: "number", header: t("Invoice", "الفاتورة"), description: () => t("Simplified tax invoice", "فاتورة ضريبية مبسطة"), cardSlot: "meta" },
{ key: "total", header: t("Total", "المجموع"), cell: (r) => <Money amount={r.total} />, align: "end", cardSlot: "end" },
{ key: "comment", header: t("Comment", "ملاحظة"), cardSlot: "block", hideable: false },
];
return <DataTable className="w-full" density="compact" cards columns={columns} rows={rows} getRowId={(r) => r.id} caption={t("Orders", "الطلبات")} hideCaption rowHref={(r) => `#${r.id}`} />;
}
/** `cardDescription: "block"`: below 768 px, the long description of the title column is a full-width block after the meta line. */| Paid (4) | ||
|---|---|---|
| INV-1043 | Sadeem | 10,750 |
| INV-1046 | Najm Logistics | 10,000 |
| INV-1049 | Raha Clinics | 9,250 |
| INV-1040 | Masar | 1,500 |
| Subtotal | 31,500 | |
| Overdue (3) | ||
| INV-1041 | Nakhla Foods | 11,250 |
| INV-1044 | Wadi Tech | 10,500 |
| INV-1047 | Masar | 9,750 |
| Subtotal | 31,500 | |
| Due (3) | ||
| INV-1042 | Raha Clinics | 11,000 |
| INV-1045 | Bayt Coffee | 10,250 |
| INV-1048 | Nakhla Foods | 9,500 |
| Subtotal | 30,750 | |
| Total | 93,750 | |
Code
export function DataTableReportExample() {
const t = useT();
const status = { paid: t("Paid", "مدفوعة"), due: t("Due", "مستحقة"), overdue: t("Overdue", "متأخرة") };
const sum = (rows: Invoice[]) => <Money amount={rows.reduce((n, r) => n + r.amount, 0)} />;
const rows = INVOICES.slice(0, 10);
return (
<DataTable
className="w-full"
columns={useInvoiceColumns().filter((c) => c.key !== "status")}
rows={rows}
getRowId={(r) => r.id}
caption={t("Invoices by status", "الفواتير حسب الحالة")}
hideCaption
defaultSort={{ key: "amount", direction: "desc" }}
groupBy={(r) => r.status}
groupHeader={(key, group) => `${status[key as Invoice["status"]]} (${group.length})`}
groupTotals={(_, group) => ({ amount: sum(group) })}
totals={{ amount: sum(rows) }}
/>
);
}
/** A print copy: small cells, wrapping headers, no scroll box, no cards. The caller leaves out pages and row links. */| Status | |||
|---|---|---|---|
| Paid (3) | |||
| INV-1040 | Masar | Paid | 1,500 |
| INV-1043 | Sadeem | Paid | 10,750 |
| INV-1046 | Najm Logistics | Paid | 10,000 |
| Subtotal | 22,250 | ||
| Overdue (3) | |||
| INV-1041 | Nakhla Foods | Overdue | 11,250 |
| INV-1044 | Wadi Tech | Overdue | 10,500 |
| INV-1047 | Masar | Overdue | 9,750 |
| Subtotal | 31,500 | ||
| Due (2) | |||
| INV-1042 | Raha Clinics | Due | 11,000 |
| INV-1045 | Bayt Coffee | Due | 10,250 |
| Subtotal | 21,250 | ||
| Total | 75,000 | ||
Code
export function DataTablePrintExample() {
const t = useT();
const status = { paid: t("Paid", "مدفوعة"), due: t("Due", "مستحقة"), overdue: t("Overdue", "متأخرة") };
const sum = (rows: Invoice[]) => <Money amount={rows.reduce((n, r) => n + r.amount, 0)} />;
const rows = INVOICES.slice(0, 8);
return (
<DataTable
className="w-full"
density="print"
columns={useInvoiceColumns().map((c) => (c.key === "amount" ? { ...c, header: <>{t("Amount including VAT (", "المبلغ شاملًا الضريبة (")}<RiyalSign />)</> } : c))}
rows={rows}
getRowId={(r) => r.id}
caption={t("Tax documents", "المستندات الضريبية")}
groupBy={(r) => r.status}
groupHeader={(key, group) => `${status[key as Invoice["status"]]} (${group.length})`}
groupTotals={(_, group) => ({ amount: sum(group) })}
totals={{ amount: sum(rows) }}
/>
);
}
/** ColumnsMenu hides columns (Invoice stays), with a rows-per-page choice and a header that stays in view. */| Client | Status | ||
|---|---|---|---|
Code
export function DataTableServerExample() {
const t = useT();
const columns = useInvoiceColumns().map((c) => (c.key === "client" ? { ...c, sortable: false } : c));
const [query, setQuery] = useState<{ sort: DataTableSort; page: number }>({ sort: { key: "id", direction: "asc" }, page: 1 });
const [loading, setLoading] = useState(true);
// A pretend request: 600 ms of loading after each sort or page change.
useEffect(() => {
setLoading(true);
const id = setTimeout(() => setLoading(false), 600);
return () => clearTimeout(id);
}, [query]);
return (
<DataTable
className="w-full"
columns={columns}
rows={fetchInvoices(query.sort, query.page)}
getRowId={(r) => r.id}
caption={t("Invoices", "الفواتير")}
hideCaption
sort={query.sort}
onSortChange={(sort) => setQuery({ sort, page: 1 })}
page={query.page}
pageCount={Math.ceil(INVOICES.length / PAGE_SIZE)}
onPageChange={(page) => setQuery({ ...query, page })}
loading={loading}
/>
);
}
type AppRow = { id: string; name: [string, string]; domain: string; status: "live" | "stopped"; owner: [string, string] };
const OWNERS = { sara: ["Sara", "سارة"], omar: ["Omar", "عمر"], lina: ["Lina", "لينا"] } as const;
const APPS: AppRow[] = (
[
[["Main website", "الموقع الرئيسي"], "shop.example.com", "live", "sara"],
[["Al Noor store", "متجر النور"], "alnoor.example.com", "live", "omar"],
[["Help center", "مركز المساعدة"], "help.example.com", "stopped", "lina"],
[["Booking portal", "بوابة الحجز"], "book.example.com", "live", "sara"],
[["Staff directory", "دليل الموظفين"], "staff.example.com", "stopped", "omar"],
[["Event pages", "صفحات الفعاليات"], "events.example.com", "live", "lina"],
[["Customer blog", "مدونة العملاء"], "blog.example.com", "live", "sara"],
[["Partner area", "منطقة الشركاء"], "partners.example.com", "stopped", "omar"],
] as const
).map(([name, domain, status, owner], i) => ({ id: `app-${i}`, name: [...name], domain, status, owner: [...OWNERS[owner]] }));
function useAppColumns(): DataTableColumn<AppRow>[] {
const t = useT();
const lang = useLang();
const k = lang === "ar" ? 1 : 0;
const status = { live: t("Live", "يعمل"), stopped: t("Not running", "متوقف") };
return [
{ key: "name", header: t("App", "التطبيق"), cell: (r) => r.name[k], sortable: true, sortValue: (r) => r.name[k] },
{ key: "domain", header: t("Address", "العنوان"), cell: (r) => <span dir="ltr" className="font-mono text-xs">{r.domain}</span> },
{ key: "status", header: t("Status", "الحالة"), cell: (r) => <StatusBadge tone={r.status === "live" ? "success" : "danger"}>{status[r.status]}</StatusBadge> },
{ key: "owner", header: t("Owner", "المسؤول"), cell: (r) => r.owner[k] },
];
}
/** `viewKey` adds a Table and Cards switch at the end of the `toolbar` row; the choice is kept in the browser. */| Status | |||
|---|---|---|---|
No invoices yet Invoices you send appear here. | |||
Code
export function DataTableEmptyExample() {
const t = useT();
return (
<DataTable
className="w-full"
columns={useInvoiceColumns()}
rows={[]}
getRowId={(r) => r.id}
caption={t("Invoices", "الفواتير")}
hideCaption
empty={
<EmptyState
className="border-0"
icon={<Receipt aria-hidden />}
title={t("No invoices yet", "لا توجد فواتير بعد")}
description={t("Invoices you send appear here.", "تظهر هنا الفواتير التي ترسلها.")}
action={
<Button size="sm">
<Plus aria-hidden />
{t("New invoice", "فاتورة جديدة")}
</Button>
}
/>
}
/>
);
}| Address | Status | Owner | |
|---|---|---|---|
| Main website | Addressshop.example.com | StatusLive | OwnerSara |
| Al Noor store | Addressalnoor.example.com | StatusLive | OwnerOmar |
| Help center | Addresshelp.example.com | StatusNot running | OwnerLina |
| Booking portal | Addressbook.example.com | StatusLive | OwnerSara |
| Staff directory | Addressstaff.example.com | StatusNot running | OwnerOmar |
| Event pages | Addressevents.example.com | StatusLive | OwnerLina |
| Customer blog | Addressblog.example.com | StatusLive | OwnerSara |
| Partner area | Addresspartners.example.com | StatusNot running | OwnerOmar |
Code
export function DataTableViewExample() {
const t = useT();
const k = useLang() === "ar" ? 1 : 0;
const [query, setQuery] = useState("");
const [filter, setFilter] = useState<FilterValue>({});
const rows = APPS.filter((r) => r.name[k].toLowerCase().includes(query.toLowerCase()) && (!filter.status?.length || filter.status.includes(r.status)));
return (
<DataTable
className="w-full"
columns={useAppColumns()}
rows={rows}
getRowId={(r) => r.id}
caption={t("Apps", "التطبيقات")}
hideCaption
cards
viewKey="docs-apps"
toolbar={
<FilterBar
search={{ value: query, onValueChange: setQuery, placeholder: t("Search apps", "ابحث في التطبيقات") }}
value={filter}
onValueChange={setFilter}
filters={[
{
key: "status",
label: t("Status", "الحالة"),
multiple: true,
options: [
{ value: "live", label: t("Live", "يعمل") },
{ value: "stopped", label: t("Not running", "متوقف") },
],
},
]}
/>
}
/>
);
}
/** The first column is a level badge and the title is in the second: `titleColumn` makes the second the row link and the card title; `rowLabel` keeps the links inside the title. */| Address | Status | Owner | Region | Plan | Created | Notes | |
|---|---|---|---|---|---|---|---|
| Main website | shop.example.com | Live | Sara | Riyadh | Standard | 2026-01-15 | No notes |
| Al Noor store | alnoor.example.com | Live | Omar | Riyadh | Standard | 2026-01-15 | No notes |
| Help center | help.example.com | Not running | Lina | Riyadh | Standard | 2026-01-15 | No notes |
| Booking portal | book.example.com | Live | Sara | Riyadh | Standard | 2026-01-15 | No notes |
A side box in the same grid.
Code
export function DataTableInGridExample() {
const t = useT();
const columns: DataTableColumn<AppRow>[] = [
...useAppColumns(),
{ key: "c5", header: t("Region", "المنطقة"), cell: () => t("Riyadh", "الرياض") },
{ key: "c6", header: t("Plan", "الباقة"), cell: () => t("Standard", "قياسية") },
{ key: "c7", header: t("Created", "أُنشئ"), cell: () => "2026-01-15" },
{ key: "c8", header: t("Notes", "ملاحظات"), cell: () => t("No notes", "لا ملاحظات") },
];
return (
<div className="grid w-full grid-cols-1 gap-4 md:grid-cols-[1fr_12rem]">
<DataTable columns={columns} rows={APPS.slice(0, 4)} getRowId={(r) => r.id} caption={t("Apps", "التطبيقات")} hideCaption />
<Card className="p-4">
<Text size="sm">{t("A side box in the same grid.", "صندوق جانبي في الشبكة نفسها.")}</Text>
</Card>
</div>
);
}| Level | Event | Time | Row actions |
|---|---|---|---|
| LevelCritical | Disk full on shop.example.comDisk full on shop.example.com | Time10:05 | |
| LevelOther | Update ready for Al NoorUpdate ready for Al Noor | Time09:40 |
Code
export function DataTableTitleExample() {
const t = useT();
const rows = [
{ id: "1", level: "critical", at: "10:05", title: t("Disk full on", "القرص ممتلئ على"), site: "shop.example.com" },
{ id: "2", level: "other", at: "09:40", title: t("Update ready for", "تحديث جاهز لـ"), site: "Al Noor" },
];
const columns: DataTableColumn<(typeof rows)[number]>[] = [
{ key: "level", header: t("Level", "المستوى"), cell: (r) => <StatusBadge tone={r.level === "critical" ? "danger" : "neutral"}>{r.level === "critical" ? t("Critical", "حرج") : t("Other", "أخرى")}</StatusBadge> },
{ key: "title", header: t("Event", "الحدث"), cell: (r) => <span>{r.title} <a href="#" className="underline">{r.site}</a></span> },
{ key: "at", header: t("Time", "الوقت") },
];
return (
<DataTable
className="w-full"
columns={columns}
rows={rows}
getRowId={(r) => r.id}
caption={t("Events", "الأحداث")}
hideCaption
cards
rowHref={(r) => `#event-${r.id}`}
titleColumn="title"
rowLabel={(r) => `${r.title} ${r.site}`}
rowActions={() => [{ label: t("Open", "فتح") }]}
/>
);
}
/** `cardTitle` gives each card its own title: the order and the customer, while the customer column is hidden on cards. */| Order | Customer | Total |
|---|---|---|
| Order 1042Order 1042 · Al Noor | CustomerAl Noor | Total49 |
| Order 1043Order 1043 · Al Amal | CustomerAl Amal | Total120 |
Code
export function DataTableCardTitleExample() {
const t = useT();
const rows = [
{ id: "1042", customer: t("Al Noor", "النور"), total: "49" },
{ id: "1043", customer: t("Al Amal", "الأمل"), total: "120" },
];
const columns: DataTableColumn<(typeof rows)[number]>[] = [
{ key: "id", header: t("Order", "الطلب"), cell: (r) => `${t("Order", "الطلب")} ${r.id}` },
{ key: "customer", header: t("Customer", "العميل"), hideOnCard: true },
{ key: "total", header: t("Total", "الإجمالي"), align: "end" },
];
return (
<DataTable
className="w-full"
columns={columns}
rows={rows}
getRowId={(r) => r.id}
caption={t("Orders", "الطلبات")}
hideCaption
cards
cardTitle={(r) => `${t("Order", "الطلب")} ${r.id} · ${r.customer}`}
/>
);
}
/** The table can shrink inside a grid box: below 768 px only the table scrolls, not the page. */| Site | Plan |
|---|---|
| Main websiteServes shop.example.com from the Riyadh region and keeps a daily backup. | Pro |
| BlogStatic pages for blog.example.com. | Basic |
Code
export function DataTableCardBlockExample() {
const t = useT();
type Site = { id: string; name: string; plan: string; note: string };
const rows: Site[] = [
{ id: "1", name: t("Main website", "الموقع الرئيسي"), plan: "Pro", note: t("Serves shop.example.com from the Riyadh region and keeps a daily backup.", "يخدم shop.example.com من منطقة الرياض ويحتفظ بنسخة احتياطية يومية.") },
{ id: "2", name: t("Blog", "المدونة"), plan: "Basic", note: t("Static pages for blog.example.com.", "صفحات ثابتة لـ blog.example.com.") },
];
const columns: DataTableColumn<Site>[] = [
{ key: "name", header: t("Site", "الموقع"), description: (r) => r.note, cardDescription: "block" },
{ key: "plan", header: t("Plan", "الباقة"), cardSlot: "meta" },
];
return <DataTable className="w-full" cards columns={columns} rows={rows} getRowId={(r) => r.id} caption={t("Sites", "المواقع")} hideCaption />;
}