Skip to main content

Table

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

A list of recent transactions.
InvoiceStatusMethodAmount
INV-001PaidCredit Card$250.00
INV-002PendingPayPal$150.00
INV-003UnpaidBank Transfer$350.00
INV-004PaidCredit Card$450.00
INV-005PaidPayPal$550.00
INV-006PendingBank Transfer$200.00
Total$1,950.00
Props
Slots

Anatomy#

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 instead. For a one-column collection, use List.

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

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.

<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.

<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.

<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 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 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.

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.

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.

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: '[email protected]',
    client: 'Ken Thompson',
  },
  {
    id: '3u1reuv4',
    amount: 242,
    status: 'success',
    email: '[email protected]',
    client: 'Abe Lincoln',
  },
  {
    id: 'derv1ws0',
    amount: 837,
    status: 'processing',
    email: '[email protected]',
    client: 'Monserrat R.',
  },
  {
    id: '5kma53ae',
    amount: 874,
    status: 'success',
    email: '[email protected]',
    client: 'Silas Marner',
  },
  {
    id: 'bhqecj4p',
    amount: 721,
    status: 'failed',
    email: '[email protected]',
    client: 'Carmella Bing',
  },
  {
    id: '728ed52f',
    amount: 100,
    status: 'pending',
    email: '[email protected]',
    client: 'Alex Smith',
  },
  {
    id: '928ed52a',
    amount: 540,
    status: 'success',
    email: '[email protected]',
    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
data-selected
Slot: table-row
Description: Present when the item or tab is selected.

Props#

Table#

Props for Table. Renders a <table> element by default.

Prop

Header#

Renders a <thead> element by default.

Prop

Body#

Renders a <tbody> element by default.

Prop

Renders a <tfoot> element by default.

Prop

Row#

Renders a <tr> element by default.

Prop

Head#

Renders a <th> element by default.

Prop

Cell#

Renders a <td> element by default.

Prop

Caption#

Renders a <caption> element by default.

Prop