---
title: Table
description: Lay out tabular data with native table parts, density and border
  variants, and row states.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Table

> Lay out tabular data with native table parts, density and border variants, and row states.

## Anatomy

```text
Table [component; slot=root; <table>]
├── Table.Caption [part; slot=caption; <caption>]
├── Table.Header [part; slot=header; <thead>]
│   └── Table.Row [part; slot=row; <tr>]
│       └── Table.Head [part; slot=head; <th>]
├── Table.Body [part; slot=body; <tbody>]
│   └── Table.Row [part; slot=row; <tr>]
│       └── Table.Cell [part; slot=cell; <td>]
└── Table.Footer [part; slot=footer; <tfoot>]
    └── Table.Row [part; slot=row; <tr>]
        └── Table.Cell [part; slot=cell; <td>]
```

The `table` sits inside a `container` element (`data-slot="table-container"`) that scrolls
horizontally, so wide tables do not stretch the page.

## Usage

Use Table to present data you lay out yourself: invoices, comparison grids, or summaries with a
known set of columns. When the table needs sorting, selection, pagination, or server data, use
[DataTable](https://moraine.subf.dev/components/data-table.md) instead. For a one-column collection, use
[List](https://moraine.subf.dev/components/list.md).

Table is a styled set of native table elements. Compose the parts in table order.

```tsx
import { Table } from 'moraine'

export function InvoiceTable() {
  return (
    <Table>
      <Table.Caption>Recent invoices</Table.Caption>
      <Table.Header>
        <Table.Row>
          <Table.Head>Invoice</Table.Head>
          <Table.Head>Status</Table.Head>
          <Table.Head align="end">Amount</Table.Head>
        </Table.Row>
      </Table.Header>
      <Table.Body>
        <Table.Row>
          <Table.Cell>INV-001</Table.Cell>
          <Table.Cell>Paid</Table.Cell>
          <Table.Cell align="end">$250.00</Table.Cell>
        </Table.Row>
      </Table.Body>
    </Table>
  )
}
```

### Parts and native attributes

Each part renders one fixed element and forwards native attributes to it.

| Part            | Element   | Own props              |
| --------------- | --------- | ---------------------- |
| `Table`         | `table`   | Variants, `wrapperRef` |
| `Table.Caption` | `caption` | None                   |
| `Table.Header`  | `thead`   | None                   |
| `Table.Body`    | `tbody`   | None                   |
| `Table.Footer`  | `tfoot`   | None                   |
| `Table.Row`     | `tr`      | `selected`             |
| `Table.Head`    | `th`      | `align`                |
| `Table.Cell`    | `td`      | `align`                |

Use native attributes for table semantics: `colSpan` and `rowSpan` on cells, and `scope="row"` on a
`Table.Head` that labels a body row. Name the table with `Table.Caption`, or with `aria-label` when
a visible caption does not fit. Place `Table.Caption` first in the markup; it renders below the
table.

```tsx
<Table.Row>
  <Table.Head scope="row">Storage</Table.Head>
  <Table.Cell>10 GB</Table.Cell>
  <Table.Cell>100 GB</Table.Cell>
</Table.Row>
```

`ref` targets the `table`; `wrapperRef` targets the element that wraps it.

### Density and borders

`size` (`'sm'`, `'md'`, or `'lg'`; default `'md'`) sets cell padding and text size. `border` draws
row dividers (`'row'`, the default), column dividers (`'col'`), or both (`'both'`). `striped` shades
alternate rows, and `highlightOnHover` highlights body rows under the pointer. Neither applies to
selected rows.

### Alignment and truncation

`align` sets text alignment on `Table.Head` and `Table.Cell`: `'start'` (default), `'center'`, or
`'end'`. Because `Table.Head` defaults to `start`, header text is not centered the way the browser
centers a plain `th`. End-align numeric columns in both the header and the cells.

To keep long text on one line with an ellipsis, add the `truncate` and `max-w-*` class to
`Table.Head` or `Table.Cell`.

```tsx
<Table.Cell class="max-w-40 truncate">{customer.address}</Table.Cell>
```

### Selected rows

`selected` on `Table.Row` applies the selected background through `data-selected`. It is visual
only: `aria-selected` is not valid on rows of a static table, so it is not set. Put a labelled
control in the row, such as a checkbox, so assistive technology knows the row is selected.

```tsx
<Table.Row selected={isSelected(invoice.id)}>
  <Table.Cell>
    <Checkbox
      checked={isSelected(invoice.id)}
      onCheckedChange={(checked) => setSelected(invoice.id, checked)}
      aria-label={`Select ${invoice.id}`}
    />
  </Table.Cell>
  <Table.Cell>{invoice.id}</Table.Cell>
</Table.Row>
```

### Building a data grid

You have two options for a sortable, filterable grid:

- **DataTable.** Use [DataTable](https://moraine.subf.dev/components/data-table.md) from `moraine/data-table`. It renders
  sorting, selection, pagination, pinning, resizing, loading states, and row virtualization from a
  `createDataTable` instance.
- **TanStack Table with Table parts.** Use [`@tanstack/table-core`](https://tanstack.com/table/latest)
  with `createTable` from `moraine/data-table` and render its header groups and rows with Table parts.
  You own every control, as in the TanStack example below.

## Examples

### Review transaction invoices

Compose a caption, header, body, and footer total. Status badges sit in a cell, and amounts are
end-aligned in both the header and the cells.

```tsx
import { Badge, Table } from 'moraine'

export function Basic() {
  return (
    <Table>
      <Table.Caption>A list of recent transactions.</Table.Caption>
      <Table.Header>
        <Table.Row>
          <Table.Head>Invoice</Table.Head>
          <Table.Head>Status</Table.Head>
          <Table.Head>Method</Table.Head>
          <Table.Head align="end">Amount</Table.Head>
        </Table.Row>
      </Table.Header>
      <Table.Body>
        <Table.Row>
          <Table.Cell class="font-medium">INV-001</Table.Cell>
          <Table.Cell>
            <Badge tone="success" variant="subtle">
              Paid
            </Badge>
          </Table.Cell>
          <Table.Cell>Credit Card</Table.Cell>
          <Table.Cell align="end">$250.00</Table.Cell>
        </Table.Row>
        <Table.Row>
          <Table.Cell class="font-medium">INV-002</Table.Cell>
          <Table.Cell>
            <Badge tone="warning" variant="subtle">
              Pending
            </Badge>
          </Table.Cell>
          <Table.Cell>PayPal</Table.Cell>
          <Table.Cell align="end">$150.00</Table.Cell>
        </Table.Row>
        <Table.Row>
          <Table.Cell class="font-medium">INV-003</Table.Cell>
          <Table.Cell>
            <Badge tone="danger" variant="subtle">
              Unpaid
            </Badge>
          </Table.Cell>
          <Table.Cell>Bank Transfer</Table.Cell>
          <Table.Cell align="end">$350.00</Table.Cell>
        </Table.Row>
      </Table.Body>
      <Table.Footer>
        <Table.Row>
          <Table.Cell colSpan={3}>Total</Table.Cell>
          <Table.Cell align="end" class="font-semibold">
            $750.00
          </Table.Cell>
        </Table.Row>
      </Table.Footer>
    </Table>
  )
}
```

### Truncate long header and cell values

Add `truncate` and a `max-w-*` class to keep long text on one line, and center or end-align
the other columns with `align`.

```tsx
import { Table } from 'moraine'

export function CustomColumns() {
  return (
    <Table>
      <Table.Header>
        <Table.Row>
          <Table.Head class="max-w-[120px] truncate">
            Very very very very very very very very Long Column Title
          </Table.Head>
          <Table.Head align="center">Centered</Table.Head>
          <Table.Head align="end">End Aligned</Table.Head>
        </Table.Row>
      </Table.Header>
      <Table.Body>
        <Table.Row>
          <Table.Cell class="max-w-[120px] truncate">
            This is a very long cell content that will be truncated
          </Table.Cell>
          <Table.Cell align="center">Middle</Table.Cell>
          <Table.Cell align="end">$99.00</Table.Cell>
        </Table.Row>
      </Table.Body>
    </Table>
  )
}
```

### Build a payments grid with TanStack Table

Create a TanStack table with sorting, filtering, selection, column visibility, and pagination
features, then render it with Table parts, `Checkbox`, `Input`, `DropdownMenu`, and `Pagination`.
To get these features without wiring them yourself, use [DataTable](https://moraine.subf.dev/components/data-table.md).

```tsx
import { Badge, Button, Checkbox, DropdownMenu, Input, Table, Pagination } from 'moraine'
import type { BadgeT, DropdownMenuT } from 'moraine'
import { createTable, FlexRender } from 'moraine/data-table'
import {
  columnFilteringFeature,
  columnVisibilityFeature,
  createFilteredRowModel,
  createPaginatedRowModel,
  createSortedRowModel,
  filterFn_includesString,
  rowPaginationFeature,
  rowSelectionFeature,
  rowSortingFeature,
  sortFn_alphanumeric,
  sortFn_text,
  tableFeatures,
} from '@tanstack/table-core'
import type {
  ColumnDef,
  ColumnFiltersState,
  ColumnVisibilityState,
  PaginationState,
  RowSelectionState,
  SortingState,
} from '@tanstack/table-core'
import { createMemo, createSignal, For, Show } from 'solid-js'

export interface Payment {
  id: string
  amount: number
  status: 'pending' | 'processing' | 'success' | 'failed'
  email: string
  client: string
}

const INITIAL_DATA: Payment[] = [
  {
    id: 'm5gr84i9',
    amount: 316,
    status: 'success',
    email: 'ken99@yahoo.com',
    client: 'Ken Thompson',
  },
  {
    id: '3u1reuv4',
    amount: 242,
    status: 'success',
    email: 'abe45@gmail.com',
    client: 'Abe Lincoln',
  },
  {
    id: 'derv1ws0',
    amount: 837,
    status: 'processing',
    email: 'monserrat44@gmail.com',
    client: 'Monserrat R.',
  },
  {
    id: '5kma53ae',
    amount: 874,
    status: 'success',
    email: 'silas22@gmail.com',
    client: 'Silas Marner',
  },
  {
    id: 'bhqecj4p',
    amount: 721,
    status: 'failed',
    email: 'carmella@hotmail.com',
    client: 'Carmella Bing',
  },
  {
    id: '728ed52f',
    amount: 100,
    status: 'pending',
    email: 'alex.smith@example.com',
    client: 'Alex Smith',
  },
  {
    id: '928ed52a',
    amount: 540,
    status: 'success',
    email: 'sarah.j@example.com',
    client: 'Sarah Jenkins',
  },
]

function getStatusBadgeTone(status: Payment['status']): BadgeT.Variants['tone'] {
  switch (status) {
    case 'success':
      return 'success'
    case 'processing':
      return 'info'
    case 'pending':
      return 'warning'
    case 'failed':
      return 'danger'
  }
}

const features = tableFeatures({
  rowSortingFeature,
  sortedRowModel: createSortedRowModel(),
  sortFns: {
    alphanumeric: sortFn_alphanumeric,
    text: sortFn_text,
  },
  columnFilteringFeature,
  filteredRowModel: createFilteredRowModel(),
  filterFns: {
    includesString: filterFn_includesString,
  },
  rowPaginationFeature,
  paginatedRowModel: createPaginatedRowModel(),
  columnVisibilityFeature,
  rowSelectionFeature,
})

export function TanStackTable() {
  const [data] = createSignal<Payment[]>(INITIAL_DATA)
  const [sorting, setSorting] = createSignal<SortingState>([])
  const [columnFilters, setColumnFilters] = createSignal<ColumnFiltersState>([])
  const [columnVisibility, setColumnVisibility] = createSignal<ColumnVisibilityState>({})
  const [rowSelection, setRowSelection] = createSignal<RowSelectionState>({})
  const [pagination, setPagination] = createSignal<PaginationState>({
    pageIndex: 0,
    pageSize: 4,
  })

  const columns: ColumnDef<typeof features, Payment>[] = [
    {
      id: 'select',
      header: (props) => (
        <Checkbox
          checked={
            props.table.getIsAllPageRowsSelected()
              ? true
              : props.table.getIsSomePageRowsSelected()
                ? 'indeterminate'
                : false
          }
          onCheckedChange={(value) => props.table.toggleAllPageRowsSelected(value)}
          aria-label="Select all rows"
        />
      ),
      cell: (props) => (
        <Checkbox
          checked={props.row.getIsSelected()}
          onCheckedChange={(value) => props.row.toggleSelected(value)}
          aria-label="Select row"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: 'client',
      header: 'Client',
      cell: (props) => <span class="font-medium">{props.row.getValue('client')}</span>,
    },
    {
      accessorKey: 'email',
      header: (props) => {
        const isSorted = () => props.column.getIsSorted()
        const sortIcon = () =>
          isSorted() === 'asc'
            ? 'i-lucide:arrow-up'
            : isSorted() === 'desc'
              ? 'i-lucide:arrow-down'
              : 'i-lucide:arrow-up-down'
        return (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => props.column.toggleSorting(isSorted() === 'asc')}
            class="h-8 -ml-3"
            trailing={sortIcon()}
          >
            Email
          </Button>
        )
      },
      cell: (props) => (
        <span class="text-muted-foreground lowercase">{props.row.getValue('email')}</span>
      ),
    },
    {
      accessorKey: 'status',
      header: 'Status',
      cell: (props) => {
        const status = () => props.row.getValue<Payment['status']>('status')
        return (
          <Badge tone={getStatusBadgeTone(status())} variant="subtle" class="capitalize">
            {status()}
          </Badge>
        )
      },
    },
    {
      accessorKey: 'amount',
      header: (props) => {
        const isSorted = () => props.column.getIsSorted()
        const sortIcon = () =>
          isSorted() === 'asc'
            ? 'i-lucide:arrow-up'
            : isSorted() === 'desc'
              ? 'i-lucide:arrow-down'
              : 'i-lucide:arrow-up-down'
        return (
          <div class="text-right">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => props.column.toggleSorting(isSorted() === 'asc')}
              class="h-8 -mr-3"
              trailing={sortIcon()}
            >
              Amount
            </Button>
          </div>
        )
      },
      cell: (props) => {
        const formatted = () => {
          const amount = Number.parseFloat(props.row.getValue('amount'))
          return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
          }).format(amount)
        }

        return <div class="font-medium text-right">{formatted()}</div>
      },
    },
    {
      id: 'actions',
      enableHiding: false,
      cell: (props) => {
        const actionItems: DropdownMenuT.Item[] = [
          {
            label: 'Copy payment ID',
            onSelect: () => navigator.clipboard.writeText(props.row.original.id),
          },
          { type: 'separator' },
          { label: 'View client' },
          { label: 'View payment details' },
        ]

        return (
          <DropdownMenu>
            <DropdownMenu.Trigger
              as={Button}
              variant="ghost"
              size="icon-sm"
              leading="i-lucide:more-horizontal"
              aria-label="Open menu"
            />
            <DropdownMenu.Content items={actionItems} />
          </DropdownMenu>
        )
      },
    },
  ]

  const table = createTable({
    features,
    columns,
    get data() {
      return data()
    },
    state: {
      get sorting() {
        return sorting()
      },
      get columnFilters() {
        return columnFilters()
      },
      get columnVisibility() {
        return columnVisibility()
      },
      get rowSelection() {
        return rowSelection()
      },
      get pagination() {
        return pagination()
      },
    },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onPaginationChange: setPagination,
  })

  const visibilityItems = createMemo<DropdownMenuT.Item[]>(() =>
    table
      .getAllColumns()
      .filter((column) => typeof column.accessorFn !== 'undefined' && column.getCanHide())
      .map((column) => ({
        type: 'checkbox',
        label: column.id,
        checked: column.getIsVisible(),
        onCheckedChange: (checked) => column.toggleVisibility(checked),
      })),
  )

  const emailFilter = () => (table.getColumn('email')?.getFilterValue() as string) ?? ''

  return (
    <div class="w-full space-y-4">
      <div class="flex gap-4 items-center justify-between">
        <Input
          placeholder="Filter emails..."
          value={emailFilter()}
          onValueChange={(v) => table.getColumn('email')?.setFilterValue(v)}
          class="max-w-xs"
        />
        <DropdownMenu>
          <DropdownMenu.Trigger
            as={Button}
            variant="outline"
            size="sm"
            class="ml-auto"
            trailing="i-lucide:chevron-down"
          >
            Columns
          </DropdownMenu.Trigger>
          <DropdownMenu.Content items={visibilityItems()} />
        </DropdownMenu>
      </div>

      {/* Fixed height */}
      <div class="h-56">
        {/* Table outer border with border radius */}
        <div class="border-1 border-border rounded-md overflow-hidden">
          <Table>
            <Table.Header>
              <For each={table.getHeaderGroups()}>
                {(headerGroup) => (
                  <Table.Row>
                    <For each={headerGroup.headers}>
                      {(header) => (
                        <Table.Head
                          colSpan={header.colSpan}
                          class={header.column.id === 'select' && 'w-5'}
                        >
                          <FlexRender header={header} />
                        </Table.Head>
                      )}
                    </For>
                  </Table.Row>
                )}
              </For>
            </Table.Header>
            <Table.Body>
              <Show
                when={table.getRowModel().rows.length > 0}
                fallback={
                  <Table.Row>
                    <Table.Cell
                      colSpan={columns.length}
                      class="text-muted-foreground text-center h-24"
                    >
                      No results.
                    </Table.Cell>
                  </Table.Row>
                }
              >
                <For each={table.getRowModel().rows}>
                  {(row) => (
                    <Table.Row selected={row.getIsSelected()}>
                      <For each={row.getVisibleCells()}>
                        {(cell) => (
                          <Table.Cell class={cell.column.id === 'select' && 'w-5'}>
                            <FlexRender cell={cell} />
                          </Table.Cell>
                        )}
                      </For>
                    </Table.Row>
                  )}
                </For>
              </Show>
            </Table.Body>
          </Table>
        </div>
      </div>

      <div class="text-sm text-muted-foreground flex items-center justify-between">
        <div class="w-full">
          {table.getFilteredSelectedRowModel().rows.length} of{' '}
          {table.getFilteredRowModel().rows.length} row(s) selected.
        </div>
        <Pagination
          class="justify-end"
          size="sm"
          page={pagination().pageIndex + 1}
          pageSize={pagination().pageSize}
          total={table.getFilteredRowModel().rows.length}
          onPageChange={(page) => table.setPageIndex(page - 1)}
        />
      </div>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-selected` | `table-row` | Present when the item or tab is selected. |

### Props

#### Table

Props for Table.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| border | 'row' \| 'col' \| 'both' \| undefined | 'row' | Which divider borders are displayed. |
| highlightOnHover | boolean \| undefined | false | Whether rows highlight on hover. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Density of table rows and cells. |
| striped | boolean \| undefined | false | Whether rows display alternating background colors. |
| wrapperRef | Ref<HTMLDivElement> \| undefined | — | Receives the `<div>` that wraps the `<table>` and scrolls it horizontally. Use `ref` for the `<table>` itself. |
| children | JSX.Element \| undefined | — | Table parts and direct content. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

#### Table.Header

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Body

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Footer

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Row

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| selected | boolean \| undefined | false | Highlights the row as selected through `data-selected`. This is presentation only and sets no<br>`aria-selected`, so expose the state to assistive technology with a labelled control in the row. |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Head

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| align | 'start' \| 'center' \| 'end' \| undefined | 'start' | Text alignment for the column header. `start` and `end` follow the writing direction, so use `end` for numeric columns. |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Cell

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| align | 'start' \| 'center' \| 'end' \| undefined | 'start' | Text alignment for the cell. `start` and `end` follow the writing direction, so use `end` for numeric columns. |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### Table.Caption

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
