# Table

Rows and columns of data, with a header, a body and a footer.

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

const builds = [
  { build: "b-4821", status: "Ready", branch: "main", duration: "1m 42s" },
  { build: "b-4820", status: "Building", branch: "fix/focus-ring", duration: "2m 05s" },
  { build: "b-4819", status: "Failed", branch: "feat/calendar", duration: "0m 38s" },
  { build: "b-4818", status: "Ready", branch: "main", duration: "1m 57s" },
  { build: "b-4817", status: "Ready", branch: "docs/theming", duration: "2m 29s" },
]

export default function TableDemo() {
  return (
    <Table>
      <TableCaption>Builds from the last 24 hours.</TableCaption>
      <TableHeader>
        <TableRow>
          <TableHead>Build</TableHead>
          <TableHead>Status</TableHead>
          <TableHead>Branch</TableHead>
          <TableHead align="end">Duration</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {builds.map((row) => (
          <TableRow key={row.build}>
            <TableHead>{row.build}</TableHead>
            <TableCell>
              <Badge variant={row.status === "Failed" ? "outline" : "secondary"}>
                {row.status}
              </Badge>
            </TableCell>
            <TableCell>{row.branch}</TableCell>
            <TableCell align="end">{row.duration}</TableCell>
          </TableRow>
        ))}
      </TableBody>
      <TableFooter>
        <TableRow>
          <TableCell colSpan={3}>Total</TableCell>
          <TableCell align="end">8m 51s</TableCell>
        </TableRow>
      </TableFooter>
    </Table>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/table
```

Needs the [arene setup](https://www.arene.style/docs/installation) first.

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation).

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/table.tsx"
   "use client"

   import { createContext, use } from "react"
   import type { ComponentProps } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"

   import {
     color,
     duration,
     ease,
     leading,
     radius,
     shadow,
     space,
     text,
   } from "@/theme/tokens.stylex"

   type TableSection = "header" | "body" | "footer"

   const TableSectionContext = createContext<TableSection>("body")

   const styles = stylex.create({
     container: {
       "--arene-table-radius": radius.xl,
       "--arene-table-panel-radius": `max(0px, calc(var(--arene-table-radius) - ${space.s1}))`,
       position: "relative",
       width: "100%",
       overflowX: "auto",
       padding: space.s1,
       borderRadius: "var(--arene-table-radius)",
       backgroundColor: color.tray,
     },
     table: {
       width: "100%",
       borderCollapse: "separate",
       borderSpacing: 0,
       captionSide: "bottom",
       isolation: "isolate",
       color: color.foreground,
       fontSize: text.sm,
       lineHeight: leading.sm,
       fontVariantNumeric: "tabular-nums",
     },
     body: {
       position: "relative",
       "::before": {
         content: "''",
         position: "absolute",
         inset: 0,
         zIndex: -1,
         borderRadius: "var(--arene-table-panel-radius)",
         backgroundColor: color.card,
         boxShadow: shadow.raised,
         pointerEvents: "none",
       },
     },
     footer: { fontWeight: 500 },
     selectedRow: { "--arene-table-row-bg": color.muted },
     bodyRow: {
       "--arene-table-row-bg": { default: color.transparent, ":hover": color.itemHighlightBg },
       "--arene-table-seam": { default: "1px", ":last-child": "0px" },
       "--arene-table-corner-start": {
         default: "0px",
         ":first-child": "var(--arene-table-panel-radius)",
       },
       "--arene-table-corner-end": {
         default: "0px",
         ":last-child": "var(--arene-table-panel-radius)",
       },
     },
     cell: {
       paddingInline: space.s3,
       paddingBlock: space.s2_5,
       textAlign: "start",
       verticalAlign: "middle",
       whiteSpace: "nowrap",
     },
     bodyCell: {
       backgroundColor: "var(--arene-table-row-bg)",
       borderBlockEndWidth: "var(--arene-table-seam)",
       borderBlockEndStyle: "solid",
       borderBlockEndColor: color.border,
       borderStartStartRadius: { default: null, ":first-child": "var(--arene-table-corner-start)" },
       borderStartEndRadius: { default: null, ":last-child": "var(--arene-table-corner-start)" },
       borderEndStartRadius: { default: null, ":first-child": "var(--arene-table-corner-end)" },
       borderEndEndRadius: { default: null, ":last-child": "var(--arene-table-corner-end)" },
       transitionProperty: "background-color",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
     },
     head: {
       paddingBlock: space.s2,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 500,
       color: color.mutedForeground,
     },
     rowHead: { fontWeight: 500 },
     caption: {
       paddingInline: space.s3,
       paddingBlockStart: space.s3,
       paddingBlockEnd: space.s2,
       color: color.mutedForeground,
       fontSize: text.xs,
       lineHeight: leading.xs,
       textAlign: "start",
     },
   })

   const aligns = stylex.create({
     start: { textAlign: "start" },
     center: { textAlign: "center" },
     end: { textAlign: "end" },
   })

   const tableStyles = {
     container: styles.container,
     table: styles.table,
     body: styles.body,
     footer: styles.footer,
     bodyRow: styles.bodyRow,
     selectedRow: styles.selectedRow,
     cell: styles.cell,
     bodyCell: styles.bodyCell,
     head: styles.head,
     caption: styles.caption,
     aligns,
   }

   type TableAlign = keyof typeof aligns

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type TableProps = useRender.ComponentProps<"table"> &
     Overrides & {
       containerProps?: ComponentProps<"div"> & Overrides
     }

   function Table({ render, ref, style, xstyle, className, containerProps, ...props }: TableProps) {
     const {
       xstyle: containerXstyle,
       className: containerClassName,
       style: containerStyle,
       ...containerRest
     } = containerProps ?? {}
     const containerSx = stylex.props(styles.container, containerXstyle)
     const sx = stylex.props(styles.table, xstyle)
     const table = useRender({
       defaultTagName: "table",
       render,
       ref,
       props: {
         "data-slot": "table",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
     return (
       <div
         data-slot="table-container"
         {...containerSx}
         {...containerRest}
         className={clsx(containerSx.className, containerClassName)}
         style={{ ...containerSx.style, ...containerStyle }}
       >
         {table}
       </div>
     )
   }

   type SectionProps<T extends "thead" | "tbody" | "tfoot"> = useRender.ComponentProps<T> & Overrides

   function TableHeader({ render, ref, style, xstyle, className, ...props }: SectionProps<"thead">) {
     const sx = stylex.props(xstyle)
     const element = useRender({
       defaultTagName: "thead",
       render,
       ref,
       props: {
         "data-slot": "table-header",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
     return <TableSectionContext value="header">{element}</TableSectionContext>
   }

   function TableBody({ render, ref, style, xstyle, className, ...props }: SectionProps<"tbody">) {
     const sx = stylex.props(styles.body, xstyle)
     const element = useRender({
       defaultTagName: "tbody",
       render,
       ref,
       props: {
         "data-slot": "table-body",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
     return <TableSectionContext value="body">{element}</TableSectionContext>
   }

   function TableFooter({ render, ref, style, xstyle, className, ...props }: SectionProps<"tfoot">) {
     const sx = stylex.props(styles.footer, xstyle)
     const element = useRender({
       defaultTagName: "tfoot",
       render,
       ref,
       props: {
         "data-slot": "table-footer",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
     return <TableSectionContext value="footer">{element}</TableSectionContext>
   }

   type TableRowProps = useRender.ComponentProps<"tr"> & Overrides & { selected?: boolean }

   function TableRow({ selected, render, ref, style, xstyle, className, ...props }: TableRowProps) {
     const section = use(TableSectionContext)
     const sx = stylex.props(
       section === "body" && styles.bodyRow,
       section === "body" && selected && styles.selectedRow,
       xstyle,
     )
     return useRender({
       defaultTagName: "tr",
       render,
       ref,
       props: {
         "data-slot": "table-row",
         "data-selected": selected || undefined,
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type CellProps<T extends "th" | "td"> = Omit<useRender.ComponentProps<T>, "align"> &
     Overrides & {
       align?: TableAlign
     }

   function TableHead({
     align = "start",
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: CellProps<"th">) {
     const section = use(TableSectionContext)
     const inBody = section === "body"
     const sx = stylex.props(
       styles.cell,
       inBody ? [styles.bodyCell, styles.rowHead] : styles.head,
       aligns[align],
       xstyle,
     )
     return useRender({
       defaultTagName: "th",
       render,
       ref,
       props: {
         "data-slot": "table-head",
         scope: inBody ? "row" : "col",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function TableCell({
     align = "start",
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: CellProps<"td">) {
     const section = use(TableSectionContext)
     const sx = stylex.props(styles.cell, section === "body" && styles.bodyCell, aligns[align], xstyle)
     return useRender({
       defaultTagName: "td",
       render,
       ref,
       props: {
         "data-slot": "table-cell",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function TableCaption({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"caption"> & Overrides) {
     const sx = stylex.props(styles.caption, xstyle)
     return useRender({
       defaultTagName: "caption",
       render,
       ref,
       props: {
         "data-slot": "table-caption",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   export {
     Table,
     TableBody,
     TableCaption,
     TableCell,
     TableFooter,
     TableHead,
     TableHeader,
     TableRow,
     tableStyles,
     type TableAlign,
   }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

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

```tsx
<Table>
  <TableCaption>Builds from the last 24 hours.</TableCaption>
  <TableHeader>
    <TableRow>
      <TableHead>Build</TableHead>
      <TableHead>Status</TableHead>
      <TableHead align="end">Duration</TableHead>
    </TableRow>
  </TableHeader>
  <TableBody>
    <TableRow>
      <TableCell>b-4821</TableCell>
      <TableCell>Ready</TableCell>
      <TableCell align="end">1m 42s</TableCell>
    </TableRow>
  </TableBody>
</Table>
```

## Composition

```text
Table
├── TableCaption
├── TableHeader
│   └── TableRow
│       └── TableHead
├── TableBody
│   └── TableRow
│       ├── TableHead
│       └── TableCell
└── TableFooter
    └── TableRow
        └── TableCell
```

The table is drawn on a tray. `TableBody` is a raised panel inside it, and
`TableHeader`, `TableFooter` and `TableCaption` stay on the tray around the
panel. Body rows highlight on hover, and a hairline divides them.

## Alignment

Set `align="end"` on the heading and the cells of a column of figures. The
table uses tabular figures, so the digits line up.

## Actions

Put a menu in the last column. A `TableHead` in a body row heads that row, as
`b-4821` does in the example above.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { HStack, VStack } from "@/components/ui/stack"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { DotsThreeIcon } from "@phosphor-icons/react/dist/csr/DotsThree"
import { Text } from "@/components/ui/text"

const members = [
  { name: "Ada Lovelace", email: "ada@example.com", initials: "AL", role: "Owner" },
  { name: "Alan Turing", email: "alan@example.com", initials: "AT", role: "Admin" },
  { name: "Emmy Noether", email: "emmy@example.com", initials: "EN", role: "Member" },
]

const styles = stylex.create({
  actions: { width: "1%" },
})

export default function TableActions() {
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Member</TableHead>
          <TableHead>Role</TableHead>
          <TableHead aria-label="Actions" xstyle={styles.actions} />
        </TableRow>
      </TableHeader>
      <TableBody>
        {members.map((member) => (
          <TableRow key={member.email}>
            <TableCell>
              <HStack gap={3} align="center">
                <Avatar>
                  <AvatarFallback>{member.initials}</AvatarFallback>
                </Avatar>
                <VStack>
                  <Text weight="medium">{member.name}</Text>
                  <Text size="xs" tone="muted">
                    {member.email}
                  </Text>
                </VStack>
              </HStack>
            </TableCell>
            <TableCell>{member.role}</TableCell>
            <TableCell align="end">
              <DropdownMenu>
                <DropdownMenuTrigger
                  render={<Button variant="ghost" size="icon-sm" />}
                  aria-label={`Actions for ${member.name}`}
                >
                  <DotsThreeIcon aria-hidden="true" />
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem>Change role</DropdownMenuItem>
                  <DropdownMenuItem>Resend invite</DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem variant="destructive">Remove</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}
```

## API reference

Pass `render` to replace a part's element or compose it with another component.

Every part renders through Base UI's
[`useRender`](https://base-ui.com/react/utils/use-render), and takes `xstyle`,
`className` and inline `style` alongside every attribute of its element.

### Table

Renders a `table` inside a `div` that draws the tray and scrolls sideways when
the columns don't fit. `xstyle`, `className` and `render` go to the `table`.

| Prop             | Type                                                                    | Default     |
| ---------------- | ----------------------------------------------------------------------- | ----------- |
| `containerProps` | `ComponentProps<"div"> & { xstyle?: StyleXStyles; className?: string }` | —           |
| `render`         | `ReactElement \| ((props, state) => ReactElement)`                      | `<table />` |
| `xstyle`         | `StyleXStyles`                                                          | —           |
| `className`      | `string`                                                                | —           |

### TableHeader, TableBody, TableFooter

Render `thead`, `tbody` and `tfoot`. Each tells its rows which section they are
in, so only body rows are raised, divided and highlighted. `TableBody` draws
the panel behind itself. The footer's text is weight 500.

### TableRow

Renders a `tr`. In the body it highlights on hover and draws a hairline below
itself. The last row has no hairline, because the panel's edge is below it.

| Prop       | Type      | Default |
| ---------- | --------- | ------- |
| `selected` | `boolean` | `false` |

`selected` fills a body row with the muted colour and writes `data-selected`.
[Data Table](https://www.arene.style/docs/components/data-table) sets it from row selection.

### TableHead

Renders a `th`. In the header it is a column label in small muted type with
`scope="col"`. In a body row it heads that row at weight 500 with
`scope="row"`. Pass `scope` to override either.

| Prop    | Type                           | Default   |
| ------- | ------------------------------ | --------- |
| `align` | `"start" \| "center" \| "end"` | `"start"` |

### TableCell

Renders a `td`. Cells don't wrap. To wrap one, pass `xstyle`.

| Prop    | Type                           | Default   |
| ------- | ------------------------------ | --------- |
| `align` | `"start" \| "center" \| "end"` | `"start"` |

### TableCaption

Renders a `caption` under the table, on the tray.

### tableStyles

The style maps behind the component. Spread them onto any element.

| Key           | What it is                                                  |
| ------------- | ----------------------------------------------------------- |
| `container`   | The tray and horizontal scroller                            |
| `table`       | The table: separate borders, type, tabular figures          |
| `body`        | The raised panel behind the body                            |
| `footer`      | The footer's weight                                         |
| `bodyRow`     | The variables a body row sets for its cells                 |
| `selectedRow` | The fill a selected body row hands its cells                |
| `cell`        | A cell's padding and alignment                              |
| `bodyCell`    | A body cell's fill, hairline and corners, read from the row |
| `head`        | A column label's type                                       |
| `caption`     | The caption                                                 |
| `aligns`      | `start`, `center` and `end`                                 |

### Data attributes

| Attribute                     | On          | Effect                            |
| ----------------------------- | ----------- | --------------------------------- |
| `data-slot="table-container"` | the tray    | Targets the tray from a parent    |
| `data-slot="table"`           | the table   | Targets the table from a parent   |
| `data-slot="table-header"`    | the header  | Targets the header from a parent  |
| `data-slot="table-body"`      | the body    | Targets the body from a parent    |
| `data-slot="table-footer"`    | the footer  | Targets the footer from a parent  |
| `data-slot="table-row"`       | a row       | Targets a row from a parent       |
| `data-selected`               | a row       | Present on a selected row         |
| `data-slot="table-head"`      | a heading   | Targets a heading from a parent   |
| `data-slot="table-cell"`      | a cell      | Targets a cell from a parent      |
| `data-slot="table-caption"`   | the caption | Targets the caption from a parent |

### CSS variables

| Variable                     | On       | Effect                                                  |
| ---------------------------- | -------- | ------------------------------------------------------- |
| `--arene-table-radius`       | the tray | The tray's corner radius, 12px. The panel's is 4px less |
| `--arene-table-panel-radius` | the tray | The panel's corner, derived from the tray's             |
