# Table

> Rows and columns on an island, with line dividers, right-aligned tabular numbers and a sideways scroll with edge fade on narrow screens.

Docs: https://plumbago.ochotzas.com/components/table

## Installation

```sh
npx plumbago add table
```

This copies `components/ui/table.tsx` into your project, along with `cn`, `scroll-fade`.

## Usage

```tsx
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

<Table>
  <TableCaption>Tonight's bookings</TableCaption>
  <TableHeader>
    <TableRow>
      <TableHead>Guest</TableHead>
      <TableHead numeric>Covers</TableHead>
    </TableRow>
  </TableHeader>
  <TableBody>
    <TableRow>
      <TableCell>Marta Silva</TableCell>
      <TableCell numeric>4</TableCell>
    </TableRow>
  </TableBody>
</Table>
```

## Examples

### Preview

```tsx
import { IslandLabel } from "@/components/ui/island"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Tag, type TagVariant } from "@/components/ui/tag"
import { useId } from "react"

const bookings: { guest: string; time: string; covers: number; table: string; status: string; variant: TagVariant }[] = [
  { guest: "Marta Silva", time: "18:30", covers: 4, table: "Window 2", status: "Seated", variant: "success" },
  { guest: "Jonas Weber", time: "19:00", covers: 2, table: "Bar 5", status: "Arriving", variant: "warning" },
  { guest: "Aiko Tanaka", time: "19:15", covers: 6, table: "Garden 1", status: "Confirmed", variant: "neutral" },
  { guest: "Leo Martin", time: "20:00", covers: 3, table: "Booth 4", status: "Cancelled", variant: "danger" },
]

export default function TableDemo() {
  const labelId = useId()

  return (
    <div className="w-full max-w-2xl">
      <IslandLabel id={labelId}>Tonight's bookings</IslandLabel>
      <Table aria-labelledby={labelId}>
        <TableHeader>
          <TableRow>
            <TableHead>Guest</TableHead>
            <TableHead>Time</TableHead>
            <TableHead numeric>Covers</TableHead>
            <TableHead>Table</TableHead>
            <TableHead align="end">Status</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {bookings.map((booking) => (
            <TableRow key={booking.guest}>
              <TableCell>{booking.guest}</TableCell>
              <TableCell className="text-ink-2 tabular-nums">{booking.time}</TableCell>
              <TableCell numeric>{booking.covers}</TableCell>
              <TableCell className="text-ink-2">{booking.table}</TableCell>
              <TableCell align="end">
                <Tag variant={booking.variant}>{booking.status}</Tag>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
```

### Numbers

```tsx
import { IslandLabel } from "@/components/ui/island"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { useId } from "react"

const dishes = [
  { dish: "Mushroom risotto", sold: 128, revenue: 1920, change: 12.4 },
  { dish: "Grilled sea bass", sold: 96, revenue: 2112, change: 4.1 },
  { dish: "Burrata with figs", sold: 74, revenue: 740, change: -3.8 },
  { dish: "Dark chocolate tart", sold: 61, revenue: 549, change: 0.6 },
]

const euro = new Intl.NumberFormat("en-IE", { style: "currency", currency: "EUR", maximumFractionDigits: 0 })

export default function TableNumbers() {
  const labelId = useId()

  return (
    <div className="w-full max-w-xl">
      <IslandLabel id={labelId}>Weekly sales by dish</IslandLabel>
      <Table aria-labelledby={labelId}>
        <TableHeader>
          <TableRow>
            <TableHead>Dish</TableHead>
            <TableHead numeric>Sold</TableHead>
            <TableHead numeric>Revenue</TableHead>
            <TableHead numeric>Change</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {dishes.map((row) => (
            <TableRow key={row.dish}>
              <TableCell>{row.dish}</TableCell>
              <TableCell numeric>{row.sold}</TableCell>
              <TableCell numeric>{euro.format(row.revenue)}</TableCell>
              <TableCell numeric className={row.change < 0 ? "text-danger" : "text-ink-2"}>
                {row.change > 0 ? "+" : ""}
                {row.change.toFixed(1)}%
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
```

### Clickable rows

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { IslandLabel, ListRowChevron } from "@/components/ui/island"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { useId, useState } from "react"

const orders = [
  { id: "A-2041", table: "Window 2", items: 5, total: "€86.50" },
  { id: "A-2042", table: "Bar 5", items: 2, total: "€31.00" },
  { id: "A-2043", table: "Garden 1", items: 9, total: "€142.80" },
]

export default function TableClickableRows() {
  const labelId = useId()
  const [opened, setOpened] = useState<(typeof orders)[number] | null>(null)

  return (
    <div className="w-full max-w-xl">
      <IslandLabel id={labelId}>Open orders</IslandLabel>
      <Table aria-labelledby={labelId}>
        <TableHeader>
          <TableRow>
            <TableHead>Order</TableHead>
            <TableHead>Table</TableHead>
            <TableHead numeric>Items</TableHead>
            <TableHead numeric>Total</TableHead>
            <TableHead className="w-0 pl-0">
              <span className="sr-only">Open</span>
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {orders.map((order) => (
            <TableRow key={order.id} onClick={() => setOpened(order)}>
              <TableCell>{order.id}</TableCell>
              <TableCell className="text-ink-2">{order.table}</TableCell>
              <TableCell numeric>{order.items}</TableCell>
              <TableCell numeric>{order.total}</TableCell>
              <TableCell className="w-0 pl-0">
                <ListRowChevron />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      <p className="mt-3 ml-1 text-footnote text-ink-2">
        <BlurSwap text={opened ? `Opened ${opened.id} for ${opened.table}` : "Pick an order to open it"} live />
      </p>
    </div>
  )
}
```

### Loading

```tsx
import { cn } from "@/lib/cn"
import { Button } from "@/components/ui/button"
import { IslandLabel } from "@/components/ui/island"
import { SkeletonText } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { useCallback, useEffect, useId, useRef, useState } from "react"

const dishes = [
  { dish: "Mushroom risotto", sold: 128, revenue: "€1,920" },
  { dish: "Grilled sea bass", sold: 96, revenue: "€2,112" },
  { dish: "Burrata with figs", sold: 74, revenue: "€740" },
]

const layer = "col-start-1 row-start-1 transition-[opacity,filter,translate,scale]"
const shown = "delay-[120ms] duration-spring ease-spring"
const hidden = "pointer-events-none opacity-0 duration-[160ms] ease-in motion-safe:-translate-y-1 motion-safe:scale-98 motion-safe:blur-[8px]"

function SalesHeader() {
  return (
    <TableHeader>
      <TableRow>
        <TableHead>Dish</TableHead>
        <TableHead numeric>Sold</TableHead>
        <TableHead numeric>Revenue</TableHead>
      </TableRow>
    </TableHeader>
  )
}

export default function TableLoading() {
  const labelId = useId()
  const [loaded, setLoaded] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  const load = useCallback(() => {
    setLoaded(false)
    clearTimeout(timer.current)
    timer.current = setTimeout(() => setLoaded(true), 1600)
  }, [])

  useEffect(() => {
    load()
    return () => clearTimeout(timer.current)
  }, [load])

  return (
    <div className="w-full max-w-xl">
      <div className="mb-2 flex items-center justify-between">
        <IslandLabel id={labelId} className="mb-0">
          Sales today
        </IslandLabel>
        <Button variant="secondary" size="sm" onClick={load} disabled={!loaded}>
          Refresh
        </Button>
      </div>
      <div className="grid">
        <Table aria-labelledby={labelId} aria-busy="true" className={cn(layer, loaded ? hidden : shown)} inert={loaded}>
          <SalesHeader />
          <TableBody>
            {dishes.map((row) => (
              <TableRow key={row.dish}>
                <TableCell>
                  <SkeletonText className="w-36" />
                </TableCell>
                <TableCell numeric>
                  <SkeletonText className="ml-auto w-8" />
                </TableCell>
                <TableCell numeric>
                  <SkeletonText className="ml-auto w-14" />
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        <Table aria-labelledby={labelId} className={cn(layer, loaded ? shown : hidden)} inert={!loaded}>
          <SalesHeader />
          <TableBody>
            {dishes.map((row) => (
              <TableRow key={row.dish}>
                <TableCell>{row.dish}</TableCell>
                <TableCell numeric>{row.sold}</TableCell>
                <TableCell numeric>{row.revenue}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}
```

### Empty

```tsx
import { Button } from "@/components/ui/button"
import { Empty, EmptyActions, EmptyDescription, EmptyIcon, EmptyTitle } from "@/components/ui/empty"
import { IslandLabel } from "@/components/ui/island"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { CalendarDays } from "lucide-react"
import { useId } from "react"

export default function TableEmpty() {
  const labelId = useId()

  return (
    <div className="w-full max-w-xl">
      <IslandLabel id={labelId}>Tonight's bookings</IslandLabel>
      <Table aria-labelledby={labelId}>
        <TableHeader>
          <TableRow>
            <TableHead>Guest</TableHead>
            <TableHead>Time</TableHead>
            <TableHead numeric>Covers</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow>
            <TableCell colSpan={3} className="font-normal">
              <Empty>
                <EmptyIcon>
                  <CalendarDays strokeWidth={1.75} />
                </EmptyIcon>
                <EmptyTitle>No bookings tonight</EmptyTitle>
                <EmptyDescription>New bookings show up here as they come in.</EmptyDescription>
                <EmptyActions>
                  <Button>Add booking</Button>
                </EmptyActions>
              </Empty>
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>
  )
}
```

### Wide

```tsx
import { IslandLabel } from "@/components/ui/island"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Tag, type TagVariant } from "@/components/ui/tag"
import { useId } from "react"

const prep: { task: string; station: string; owner: string; due: string; minutes: number; status: string; variant: TagVariant }[] = [
  { task: "Make the veal jus", station: "Sauce", owner: "Marta Rossi", due: "Before 16:00", minutes: 90, status: "Late", variant: "danger" },
  { task: "Portion the sea bass", station: "Fish", owner: "Jonas Weber", due: "Before 17:00", minutes: 40, status: "Due soon", variant: "warning" },
  { task: "Roll the fresh pasta", station: "Pasta", owner: "Ana Lima", due: "Before 17:30", minutes: 60, status: "To do", variant: "neutral" },
  { task: "Bake the focaccia", station: "Pastry", owner: "Tom Okafor", due: "Before 18:00", minutes: 45, status: "Done", variant: "success" },
]

export default function TableWide() {
  const labelId = useId()

  return (
    <div className="w-full max-w-3xl">
      <IslandLabel id={labelId}>Prep before service</IslandLabel>
      <Table aria-labelledby={labelId} className="max-w-full">
        <TableHeader>
          <TableRow>
            <TableHead>Task</TableHead>
            <TableHead className="min-w-28">Station</TableHead>
            <TableHead className="min-w-32">Owner</TableHead>
            <TableHead>Due</TableHead>
            <TableHead numeric>Minutes</TableHead>
            <TableHead align="end">Status</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {prep.map((row) => (
            <TableRow key={row.task}>
              <TableCell className="whitespace-nowrap">{row.task}</TableCell>
              <TableCell>{row.station}</TableCell>
              <TableCell className="whitespace-nowrap text-ink-2">{row.owner}</TableCell>
              <TableCell className="whitespace-nowrap text-ink-2 tabular-nums">{row.due}</TableCell>
              <TableCell numeric>{row.minutes}</TableCell>
              <TableCell align="end">
                <Tag variant={row.variant}>{row.status}</Tag>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
```

### Beside a stat

```tsx
import { Island, IslandLabel } from "@/components/ui/island"
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { useId } from "react"

const tables = [
  { name: "Window 2", covers: 4, spend: "€86.50" },
  { name: "Bar 5", covers: 2, spend: "€31.00" },
  { name: "Garden 1", covers: 6, spend: "€142.80" },
]

export default function TableBesideAStat() {
  const labelId = useId()

  return (
    <div className="grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]">
      <div className="flex flex-col">
        <IslandLabel>Tonight</IslandLabel>
        <Island className="flex flex-1 flex-col justify-between gap-6">
          <Stat>
            <StatValue>€260</StatValue>
            <StatLabel>revenue so far</StatLabel>
          </Stat>
          <p className="text-footnote text-ink-2">3 tables · 12 covers</p>
        </Island>
      </div>
      <div>
        <IslandLabel id={labelId}>Spend by table</IslandLabel>
        <Table aria-labelledby={labelId}>
          <TableHeader>
            <TableRow>
              <TableHead>Table</TableHead>
              <TableHead numeric>Covers</TableHead>
              <TableHead numeric>Spend</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {tables.map((row) => (
              <TableRow key={row.name}>
                <TableCell>{row.name}</TableCell>
                <TableCell numeric>{row.covers}</TableCell>
                <TableCell numeric>{row.spend}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}
```

## Source

```tsx
import { cn } from "@/lib/cn"
import { ScrollFade } from "@/components/ui/scroll-fade"
import type { ComponentProps, KeyboardEvent } from "react"

type PartProps<T extends keyof React.JSX.IntrinsicElements> = Omit<ComponentProps<T>, "className"> & { className?: string }

type CellAlignment = {
  align?: "start" | "end"
  numeric?: boolean
}

function alignmentClasses({ align, numeric }: CellAlignment) {
  return cn(numeric || align === "end" ? "text-right" : "text-left", numeric && "tabular-nums")
}

export type TableProps = PartProps<"table">

export function Table({ className, children, ...props }: TableProps) {
  return (
    <div data-slot="table-island" className={cn("on-surface overflow-hidden rounded-lg bg-surface", className)}>
      <ScrollFade orientation="horizontal" sidewaysWheel={false} className="@container">
        <table data-slot="table" className="w-max min-w-[max(100cqw,22rem)] border-collapse text-body text-ink" {...props}>
          {children}
        </table>
      </ScrollFade>
    </div>
  )
}

export type TableCaptionProps = PartProps<"caption"> & {
  visible?: boolean
}

export function TableCaption({ visible = false, className, ...props }: TableCaptionProps) {
  return <caption data-slot="table-caption" className={cn(visible ? "px-4 pt-4 pb-1 text-left text-headline text-ink" : "sr-only", className)} {...props} />
}

export function TableHeader({ className, ...props }: PartProps<"thead">) {
  return <thead data-slot="table-header" className={cn(className)} {...props} />
}

export function TableBody({ className, ...props }: PartProps<"tbody">) {
  return <tbody data-slot="table-body" className={cn(className)} {...props} />
}

export type TableRowProps = PartProps<"tr"> & {
  onClick?: ComponentProps<"tr">["onClick"]
}

export function TableRow({ onClick, onKeyDown, className, ...props }: TableRowProps) {
  const interactive = onClick !== undefined

  function handleKeyDown(event: KeyboardEvent<HTMLTableRowElement>) {
    onKeyDown?.(event)
    if (event.defaultPrevented || event.target !== event.currentTarget) return
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault()
      event.currentTarget.click()
    }
  }

  return (
    <tr
      data-slot="table-row"
      data-interactive={interactive ? "" : undefined}
      tabIndex={interactive ? 0 : undefined}
      onClick={onClick}
      onKeyDown={interactive ? handleKeyDown : onKeyDown}
      className={cn(
        "data-interactive:cursor-pointer data-interactive:transition-colors data-interactive:duration-fast data-interactive:ease-out data-interactive:hover:bg-press data-interactive:active:bg-line",
        "data-interactive:hover:[&>td]:border-t-transparent [[data-interactive]:hover+&]:[&>td]:border-t-transparent",
        "data-interactive:focus-visible:outline-2 data-interactive:focus-visible:-outline-offset-2 data-interactive:focus-visible:outline-ring",
        className,
      )}
      {...props}
    />
  )
}

export type TableHeadProps = Omit<PartProps<"th">, "align"> & CellAlignment

export function TableHead({ align, numeric, scope = "col", className, ...props }: TableHeadProps) {
  return (
    <th
      data-slot="table-head"
      scope={scope}
      className={cn("px-4 pt-3 pb-2 text-caption font-medium whitespace-nowrap text-ink-2", alignmentClasses({ align, numeric }), className)}
      {...props}
    />
  )
}

export type TableCellProps = Omit<PartProps<"td">, "align"> & CellAlignment

export function TableCell({ align, numeric, className, ...props }: TableCellProps) {
  return (
    <td
      data-slot="table-cell"
      className={cn(
        "border-t border-line px-4 py-3 align-middle transition-[border-color] duration-fast ease-out first:font-medium",
        alignmentClasses({ align, numeric }),
        className,
      )}
      {...props}
    />
  )
}
```
