Skip to content
Niko Table

Orders Table

An orders screen with live totals, payment and fulfillment filters, a price slider, a date range, expandable rows with line items, and ship and refund actions.

Built only from Niko Table pieces and shadcn/ui components. Install it, then swap the sample data for your own.

Installation

pnpm dlx shadcn@latest add @niko-table/orders-table

Preview

npx shadcn@latest add @niko-table/orders-table
orders-table.tsx
"use client"
import * as React from "react"
import { DataTableRoot } from "@/components/niko-table/core/data-table-root"
import { DataTable } from "@/components/niko-table/core/data-table"
import {
DataTableBody,
DataTableEmptyBody,
DataTableHeader,
} from "@/components/niko-table/core/data-table-structure"
import { useDataTable } from "@/components/niko-table/core/data-table-context"
import { DataTableColumnHeader } from "@/components/niko-table/components/data-table-column-header"
import { DataTableColumnTitle } from "@/components/niko-table/components/data-table-column-title"
import { DataTableColumnSortMenu } from "@/components/niko-table/components/data-table-column-sort"
import { DataTableToolbarSection } from "@/components/niko-table/components/data-table-toolbar-section"
import { DataTableSearchFilter } from "@/components/niko-table/components/data-table-search-filter"
import { DataTableFacetedFilter } from "@/components/niko-table/components/data-table-faceted-filter"
import { DataTableSliderFilter } from "@/components/niko-table/components/data-table-slider-filter"
import { DataTableDateFilter } from "@/components/niko-table/components/data-table-date-filter"
import { DataTableClearFilter } from "@/components/niko-table/components/data-table-clear-filter"
import { DataTableViewMenu } from "@/components/niko-table/components/data-table-view-menu"
import { DataTableExportButton } from "@/components/niko-table/components/data-table-export-button"
import { DataTableSelectionBar } from "@/components/niko-table/components/data-table-selection-bar"
import { DataTablePagination } from "@/components/niko-table/components/data-table-pagination"
import {
DataTableEmptyDescription,
DataTableEmptyFilteredMessage,
DataTableEmptyIcon,
DataTableEmptyMessage,
DataTableEmptyTitle,
} from "@/components/niko-table/components/data-table-empty-state"
import {
DataTableRowMenuScope,
RowMenuItem,
RowMenuSeparator,
useDataTableRow,
} from "@/components/niko-table/components/data-table-row-menu"
import { DataTableRowContextMenuSlot } from "@/components/niko-table/components/data-table-row-context-menu-slot"
import { SYSTEM_COLUMN_IDS } from "@/components/niko-table/lib/constants"
import type { DataTableColumnDef } from "@/components/niko-table/types"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/niko-table/primitives/button"
import { Checkbox } from "@/components/niko-table/primitives/checkbox"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/niko-table/primitives/dropdown-menu"
import {
ChevronRight,
MoreHorizontal,
PackageCheck,
PackageSearch,
SearchX,
} from "lucide-react"
import { cn } from "@/lib/utils"
import {
channelLabels,
fulfillmentOptions,
orders as sampleOrders,
paymentOptions,
type Order,
} from "./orders-data"
import {
formatPlacedAt,
fulfillmentStyle,
money,
paymentDot,
} from "./orders-format"
import { OrderDetails } from "./order-details"
const canShip = (order: Order) =>
order.payment === "paid" && order.fulfillment === "unfulfilled"
/*
* Row actions: one small piece per action, each reading its row from context.
* `OrdersTable` composes them into ONE fragment that both the "⋯" dropdown
* and the right-click menu render.
*/
function MarkShippedItem({ onShip }: { onShip: (ids: string[]) => void }) {
const order = useDataTableRow<Order>()
return (
<RowMenuItem disabled={!canShip(order)} onClick={() => onShip([order.id])}>
Mark as shipped
</RowMenuItem>
)
}
function CopyOrderIdItem({ onCopied }: { onCopied: (id: string) => void }) {
const order = useDataTableRow<Order>()
return (
<RowMenuItem
onClick={() => {
void navigator.clipboard?.writeText(order.id)
onCopied(order.id)
}}
>
Copy order ID
</RowMenuItem>
)
}
function RefundItem({ onRefund }: { onRefund: (order: Order) => void }) {
const order = useDataTableRow<Order>()
return (
<RowMenuItem
variant="destructive"
disabled={order.payment !== "paid"}
onClick={() => onRefund(order)}
>
Refund order
</RowMenuItem>
)
}
function sortableHeader() {
return (
<DataTableColumnHeader>
<DataTableColumnTitle />
<DataTableColumnSortMenu />
</DataTableColumnHeader>
)
}
function useOrderColumns(rowMenu: React.ReactNode) {
return React.useMemo<DataTableColumnDef<Order>[]>(
() => [
{
id: SYSTEM_COLUMN_IDS.SELECT,
size: 40,
enableSorting: false,
enableHiding: false,
header: ({ table }) => (
<Checkbox
// Plain boolean: Radix and Base UI checkboxes take indeterminate differently.
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all orders on this page"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={value => row.toggleSelected(!!value)}
aria-label={`Select order ${row.original.id}`}
/>
),
},
{
// An `expand` column with `expandedContent` turns on row expansion.
id: SYSTEM_COLUMN_IDS.EXPAND,
size: 40,
enableSorting: false,
enableHiding: false,
header: () => null,
cell: ({ row }) => (
<Button
variant="ghost"
size="icon"
className="size-7"
onClick={row.getToggleExpandedHandler()}
aria-expanded={row.getIsExpanded()}
aria-label={`${row.getIsExpanded() ? "Hide" : "Show"} items in order ${row.original.id}`}
>
<ChevronRight
className={cn(
"size-4 transition-transform",
row.getIsExpanded() && "rotate-90",
)}
/>
</Button>
),
meta: {
expandedContent: (order: Order) => <OrderDetails order={order} />,
},
},
{
accessorKey: "id",
meta: { label: "Order" },
header: sortableHeader,
cell: ({ row }) => (
<div className="flex flex-col">
<span className="font-mono font-medium">{row.original.id}</span>
<span className="text-xs text-muted-foreground">
{channelLabels[row.original.channel]}
</span>
</div>
),
},
{
accessorKey: "customer",
meta: { label: "Customer" },
header: sortableHeader,
cell: ({ row }) => (
<div className="flex flex-col">
<span className="font-medium">{row.original.customer}</span>
<span className="text-xs text-muted-foreground">
{row.original.city}
</span>
</div>
),
},
{
accessorKey: "placedAt",
meta: { label: "Placed", variant: "dateRange" },
header: sortableHeader,
enableColumnFilter: true,
cell: ({ row }) => {
const { date, time } = formatPlacedAt(row.original.placedAt)
return (
<div className="flex flex-col tabular-nums">
<span>{date}</span>
<span className="text-xs text-muted-foreground">{time}</span>
</div>
)
},
},
{
accessorKey: "payment",
meta: { label: "Payment", options: paymentOptions },
header: sortableHeader,
enableColumnFilter: true,
cell: ({ row }) => (
<span className="flex items-center gap-2 capitalize">
<span
className={cn(
"size-2 rounded-full",
paymentDot[row.original.payment],
)}
aria-hidden="true"
/>
{row.original.payment}
</span>
),
},
{
accessorKey: "fulfillment",
meta: { label: "Fulfillment", options: fulfillmentOptions },
header: sortableHeader,
enableColumnFilter: true,
cell: ({ row }) => (
<Badge
variant="outline"
className={cn(
"capitalize",
fulfillmentStyle[row.original.fulfillment],
)}
>
{row.original.fulfillment}
</Badge>
),
},
{
id: "items",
accessorFn: order =>
order.items.reduce((sum, item) => sum + item.quantity, 0),
meta: { label: "Items" },
header: sortableHeader,
cell: ({ getValue }) => (
<span className="text-muted-foreground tabular-nums">
{getValue<number>()}
</span>
),
},
{
accessorKey: "total",
meta: { label: "Total", unit: "$", variant: "range" },
header: sortableHeader,
enableColumnFilter: true,
cell: ({ row }) => (
<span
className={cn(
"font-medium tabular-nums",
row.original.payment === "refunded" &&
"text-muted-foreground line-through",
)}
>
{money.format(row.original.total)}
</span>
),
},
{
id: "actions",
size: 56,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-8"
aria-label={`Open actions for order ${row.original.id}`}
>
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DataTableRowMenuScope row={row.original} surface="dropdown">
{rowMenu}
</DataTableRowMenuScope>
</DropdownMenuContent>
</DropdownMenu>
</div>
),
},
],
[rowMenu],
)
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg border bg-background px-3 py-2">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-base font-semibold tabular-nums">{value}</span>
</div>
)
}
/** Totals for the rows that match the current filters. */
function OrdersSummary() {
const { table } = useDataTable<Order>()
const rows = table.getFilteredRowModel().rows.map(row => row.original)
const paid = rows.filter(order => order.payment === "paid")
const pending = rows.filter(order => order.payment === "pending")
const sum = (list: Order[]) =>
list.reduce((total, order) => total + order.total, 0)
return (
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
<Stat label="Orders" value={rows.length.toString()} />
<Stat label="Paid revenue" value={money.format(sum(paid))} />
<Stat label="Awaiting payment" value={money.format(sum(pending))} />
<Stat label="To ship" value={rows.filter(canShip).length.toString()} />
</div>
)
}
function OrdersSelectionBar({ onShip }: { onShip: (ids: string[]) => void }) {
const { table } = useDataTable<Order>()
const selected = table.getFilteredSelectedRowModel().rows
const shippable = selected.filter(row => canShip(row.original))
return (
<DataTableSelectionBar
selectedCount={selected.length}
onClear={() => table.resetRowSelection()}
>
<Button
size="sm"
variant="outline"
disabled={shippable.length === 0}
onClick={() => {
onShip(shippable.map(row => row.original.id))
table.resetRowSelection()
}}
>
<PackageCheck className="size-4" aria-hidden="true" />
Mark {shippable.length} as shipped
</Button>
</DataTableSelectionBar>
)
}
export default function OrdersTable() {
const [orders, setOrders] = React.useState(sampleOrders)
const [lastAction, setLastAction] = React.useState("")
const markShipped = React.useCallback((ids: string[]) => {
setOrders(rows =>
rows.map(order =>
ids.includes(order.id) && canShip(order)
? { ...order, fulfillment: "shipped" }
: order,
),
)
setLastAction(
ids.length === 1
? `Order ${ids[0]} marked as shipped`
: `${ids.length} orders marked as shipped`,
)
}, [])
const refund = React.useCallback((order: Order) => {
setOrders(rows =>
rows.map(row =>
row.id === order.id ? { ...row, payment: "refunded" } : row,
),
)
setLastAction(`Refunded ${money.format(order.total)} for ${order.id}`)
}, [])
// The row actions, composed ONCE and mounted in both the "⋯" dropdown and
// the right-click menu.
const rowMenu = React.useMemo(
() => (
<>
<MarkShippedItem onShip={markShipped} />
<CopyOrderIdItem onCopied={id => setLastAction(`Copied ${id}`)} />
<RowMenuSeparator />
<RefundItem onRefund={refund} />
</>
),
[markShipped, refund],
)
const columns = useOrderColumns(rowMenu)
return (
<div className="w-full rounded-xl border bg-card p-4 text-card-foreground shadow-sm">
<DataTableRoot
data={orders}
columns={columns}
getRowId={order => order.id}
// TanStack only expands rows with sub-rows unless told otherwise.
getRowCanExpand={row => row.original.items.length > 0}
>
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex flex-col gap-0.5">
<h2 className="text-base font-semibold">Orders</h2>
<p className="text-sm text-muted-foreground">
Last 60 days, newest first. Expand a row to see its items.
</p>
</div>
<DataTableExportButton filename="orders" useHeaderLabels />
</div>
<OrdersSummary />
<DataTableToolbarSection className="flex-wrap px-0">
<DataTableSearchFilter
placeholder="Search orders..."
className="min-w-48 flex-none sm:w-64"
/>
<DataTableFacetedFilter accessorKey="payment" multiple />
<DataTableFacetedFilter accessorKey="fulfillment" multiple />
<DataTableSliderFilter accessorKey="total" />
<DataTableDateFilter accessorKey="placedAt" multiple />
<DataTableClearFilter />
<div className="ml-auto">
<DataTableViewMenu />
</div>
</DataTableToolbarSection>
<OrdersSelectionBar onShip={markShipped} />
<DataTable>
<DataTableHeader />
<DataTableBody>
<DataTableRowContextMenuSlot>
{rowMenu}
</DataTableRowContextMenuSlot>
<DataTableEmptyBody>
<DataTableEmptyMessage>
<DataTableEmptyIcon>
<PackageSearch className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>No orders yet</DataTableEmptyTitle>
<DataTableEmptyDescription>
New orders show up here as soon as they are placed.
</DataTableEmptyDescription>
</DataTableEmptyMessage>
<DataTableEmptyFilteredMessage>
<DataTableEmptyIcon>
<SearchX className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>No matching orders</DataTableEmptyTitle>
<DataTableEmptyDescription>
Try a different search or clear the filters.
</DataTableEmptyDescription>
</DataTableEmptyFilteredMessage>
</DataTableEmptyBody>
</DataTableBody>
</DataTable>
<DataTablePagination />
{lastAction && (
<p className="text-xs text-muted-foreground" aria-live="polite">
{lastAction}
</p>
)}
</div>
</DataTableRoot>
</div>
)
}
order-details.tsx
"use client"
import type { Order } from "./orders-data"
import { channelLabels } from "./orders-data"
import { money } from "./orders-format"
function Row({
label,
value,
strong,
}: {
label: string
value: string
strong?: boolean
}) {
return (
<div className="flex justify-between gap-6">
<dt className={strong ? "font-medium" : "text-muted-foreground"}>
{label}
</dt>
<dd className={strong ? "font-medium tabular-nums" : "tabular-nums"}>
{value}
</dd>
</div>
)
}
/** Shown when an order row is expanded: what was bought and where it goes. */
export function OrderDetails({ order }: { order: Order }) {
return (
<div className="grid gap-6 bg-muted/30 px-4 py-4 text-sm md:grid-cols-[1fr_16rem] md:pl-14">
<div className="flex flex-col gap-2">
<h4 className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Items
</h4>
<ul className="divide-y rounded-md border bg-background">
{order.items.map(item => (
<li
key={item.sku}
className="flex items-center justify-between gap-4 px-3 py-2"
>
<div className="flex min-w-0 flex-col">
<span className="truncate">{item.product}</span>
<span className="font-mono text-xs text-muted-foreground">
{item.sku}
</span>
</div>
<span className="shrink-0 text-muted-foreground tabular-nums">
{item.quantity} × {money.format(item.unitPrice)}
</span>
<span className="w-20 shrink-0 text-right font-medium tabular-nums">
{money.format(item.quantity * item.unitPrice)}
</span>
</li>
))}
</ul>
</div>
<div className="flex flex-col gap-4">
<dl className="flex flex-col gap-1">
<Row label="Subtotal" value={money.format(order.subtotal)} />
<Row
label="Shipping"
value={order.shipping === 0 ? "Free" : money.format(order.shipping)}
/>
<Row label="Tax" value={money.format(order.tax)} />
<div className="my-1 border-t" />
<Row label="Total" value={money.format(order.total)} strong />
</dl>
<dl className="flex flex-col gap-1">
<Row label="Ships to" value={order.city} />
<Row label="Channel" value={channelLabels[order.channel]} />
<Row label="Contact" value={order.email} />
</dl>
</div>
</div>
)
}
orders-format.ts
import type { FulfillmentStatus, PaymentStatus } from "./orders-data"
export const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
})
const dateFormat = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
})
const timeFormat = new Intl.DateTimeFormat("en-US", {
hour: "numeric",
minute: "2-digit",
timeZone: "UTC",
})
export function formatPlacedAt(date: Date) {
return { date: dateFormat.format(date), time: timeFormat.format(date) }
}
export const paymentDot: Record<PaymentStatus, string> = {
paid: "bg-success",
pending: "bg-warning",
refunded: "bg-muted-foreground",
}
export const fulfillmentStyle: Record<FulfillmentStatus, string> = {
unfulfilled: "border-warning/40 text-warning",
shipped: "border-border text-foreground",
delivered: "border-success/40 text-success",
}
orders-data.ts
export type PaymentStatus = "paid" | "pending" | "refunded"
export type FulfillmentStatus = "unfulfilled" | "shipped" | "delivered"
export type SalesChannel = "web" | "mobile" | "pos"
export type LineItem = {
sku: string
product: string
quantity: number
unitPrice: number
}
export type Order = {
id: string
customer: string
email: string
city: string
channel: SalesChannel
placedAt: Date
items: LineItem[]
subtotal: number
shipping: number
tax: number
/** subtotal + shipping + tax, in USD. */
total: number
payment: PaymentStatus
fulfillment: FulfillmentStatus
}
export const paymentOptions = [
{ label: "Paid", value: "paid" },
{ label: "Pending", value: "pending" },
{ label: "Refunded", value: "refunded" },
]
export const fulfillmentOptions = [
{ label: "Unfulfilled", value: "unfulfilled" },
{ label: "Shipped", value: "shipped" },
{ label: "Delivered", value: "delivered" },
]
export const channelLabels: Record<SalesChannel, string> = {
web: "Online store",
mobile: "Mobile app",
pos: "In store",
}
/**
* Sample data, generated rather than hand-written. A seeded PRNG (mulberry32)
* keeps it random-looking but identical on every render. Swap `orders` for
* your own rows.
*/
function seededRandom(seed: number) {
let a = seed
return () => {
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const catalog = [
{ sku: "HM-104", product: "Linen throw blanket", price: 68 },
{ sku: "HM-221", product: "Stoneware mug, set of 4", price: 42 },
{ sku: "HM-307", product: "Oak desk organizer", price: 55 },
{ sku: "AP-012", product: "Merino beanie", price: 29 },
{ sku: "AP-045", product: "Canvas tote", price: 24 },
{ sku: "OD-118", product: "Insulated trail bottle", price: 34 },
{ sku: "OD-160", product: "Packable rain shell", price: 129 },
{ sku: "ST-009", product: "Dot-grid notebook", price: 16 },
{ sku: "ST-031", product: "Brass desk lamp", price: 96 },
{ sku: "ST-077", product: "Fountain pen", price: 58 },
]
const firstNames = [
"Arlo",
"Bea",
"Cyrus",
"Dalia",
"Emil",
"Fern",
"Gus",
"Hazel",
"Ivo",
"June",
"Kofi",
"Lior",
"Mira",
"Nico",
"Opal",
"Remy",
"Saoirse",
"Teo",
"Vera",
"Wes",
]
const lastNames = [
"Albright",
"Brandt",
"Costa",
"Dube",
"Ekström",
"Fontaine",
"Greco",
"Haddad",
"Iwu",
"Jovanović",
"Kim",
"Laurent",
"Mbeki",
"Nygaard",
"Okafor",
"Pires",
"Ruiz",
"Sorensen",
"Toivonen",
"Vance",
]
const cities = [
"Toronto",
"Lisbon",
"Austin",
"Melbourne",
"Berlin",
"Nairobi",
"Osaka",
"Montréal",
"Copenhagen",
"Bogotá",
]
const channels: SalesChannel[] = [
"web",
"web",
"web",
"mobile",
"mobile",
"pos",
]
const round = (value: number) => Math.round(value * 100) / 100
function generateOrders(count: number, seed: number): Order[] {
const random = seededRandom(seed)
const pick = <T>(items: readonly T[]) =>
items[Math.floor(random() * items.length)]
// Fixed reference time so generated dates never shift between renders.
const now = Date.UTC(2026, 10, 1, 18)
return (
Array.from({ length: count }, () => {
const first = pick(firstNames)
const last = pick(lastNames)
const lines = 1 + Math.floor(random() * 4)
const items: LineItem[] = []
for (let l = 0; l < lines; l++) {
const item = pick(catalog)
if (items.some(existing => existing.sku === item.sku)) continue
items.push({
sku: item.sku,
product: item.product,
quantity: 1 + Math.floor(random() * 3),
unitPrice: item.price,
})
}
const subtotal = items.reduce(
(sum, item) => sum + item.quantity * item.unitPrice,
0,
)
const shipping = subtotal >= 150 ? 0 : 9
const tax = round(subtotal * 0.08)
// Squared so recent orders are more common, like a real store.
const ageHours = Math.floor(random() ** 2 * 24 * 60)
const roll = random()
const payment: PaymentStatus =
roll < 0.78 ? "paid" : roll < 0.92 ? "pending" : "refunded"
// Recent paid orders are still waiting to ship; older ones have moved on.
const fulfillment: FulfillmentStatus =
payment !== "paid"
? "unfulfilled"
: ageHours < 48
? "unfulfilled"
: ageHours < 24 * 7
? pick(["unfulfilled", "shipped"] as const)
: pick(["shipped", "delivered", "delivered"] as const)
return {
id: "",
customer: `${first} ${last}`,
email:
`${first}.${last}`
.toLowerCase()
.normalize("NFD")
.replace(/[^\w.]/g, "") + "@example.com",
city: pick(cities),
channel: pick(channels),
placedAt: new Date(now - ageHours * 3_600_000),
items,
subtotal,
shipping,
tax,
total: round(subtotal + shipping + tax),
payment,
fulfillment,
}
})
.sort((a, b) => b.placedAt.getTime() - a.placedAt.getTime())
// Number after sorting so newer orders have higher numbers.
.map((order, i) => ({ ...order, id: `#${4820 + count - i}` }))
)
}
export const orders = generateOrders(48, 4821)

Usage

The files land in components/orders-table/. Render the block anywhere:

import OrdersTable from "@/components/orders-table/orders-table"
export default function Page() {
return <OrdersTable />
}

Then replace the generated rows in orders-data.ts with your own data, or load it from your API and pass it in.