Skip to content

ComponentsForms & data

SourceSource

Table

A bordered data table with sortable headings, selectable rows and a caption.

Use it for records that share the same fields and that a reader compares down a column: an audit log, a member list with roles and join dates, command usage. For a handful of label and value pairs, a list reads better.

It styles a native <table> and adds nothing between you and the markup. Sorting is yours: a heading reports that it was pressed and shows the order you tell it, and the rows are whatever you render.

Root class newt-table
"use client"

import * as React from "react"

import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/registry/bases/newt/ui/table"

const ACTIONS = [
  { member: "kai", action: "Warning", minutes: 0 },
  { member: "ada", action: "Timeout", minutes: 10 },
  { member: "mio", action: "Timeout", minutes: 60 },
]

type Column = "member" | "minutes"

export default function TableDemo() {
  const [column, setColumn] = React.useState<Column>("member")
  const [ascending, setAscending] = React.useState(true)

  const rows = ACTIONS.toSorted((a, b) => {
    const order =
      column === "member"
        ? a.member.localeCompare(b.member)
        : a.minutes - b.minutes
    return ascending ? order : -order
  })

  const sortOf = (target: Column) =>
    column !== target ? "none" : ascending ? "ascending" : "descending"
  const sortBy = (target: Column) => {
    setAscending(column === target ? !ascending : true)
    setColumn(target)
  }

  return (
    <Table wrapperClassName="max-w-md">
      <TableCaption>Recent moderation actions</TableCaption>
      <TableHeader>
        <tr>
          <TableHead sort={sortOf("member")} onSort={() => sortBy("member")}>
            Member
          </TableHead>
          <TableHead>Action</TableHead>
          <TableHead
            align="end"
            sort={sortOf("minutes")}
            onSort={() => sortBy("minutes")}
          >
            Minutes
          </TableHead>
        </tr>
      </TableHeader>
      <TableBody>
        {rows.map((row) => (
          <TableRow key={row.member}>
            <TableCell className="font-medium text-newt-text-primary">
              {row.member}
            </TableCell>
            <TableCell>{row.action}</TableCell>
            <TableCell align="end">{row.minutes}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}
<script setup lang="ts">
import { computed, ref } from "vue"
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  type TableSort,
} from "~~/registry/bases/newt/ui/table"

const ACTIONS = [
  { member: "kai", action: "Warning", minutes: 0 },
  { member: "ada", action: "Timeout", minutes: 10 },
  { member: "mio", action: "Timeout", minutes: 60 },
]

type Column = "member" | "minutes"

const column = ref<Column>("member")
const ascending = ref(true)

const rows = computed(() =>
  ACTIONS.toSorted((a, b) => {
    const order =
      column.value === "member"
        ? a.member.localeCompare(b.member)
        : a.minutes - b.minutes
    return ascending.value ? order : -order
  })
)

function sortOf(target: Column): TableSort {
  if (column.value !== target) return "none"
  return ascending.value ? "ascending" : "descending"
}

function sortBy(target: Column) {
  ascending.value = column.value === target ? !ascending.value : true
  column.value = target
}
</script>

<template>
  <Table wrapper-class="max-w-md">
    <TableCaption>Recent moderation actions</TableCaption>
    <TableHeader>
      <tr>
        <TableHead :sort="sortOf('member')" @sort="sortBy('member')">
          Member
        </TableHead>
        <TableHead>Action</TableHead>
        <TableHead
          align="end"
          :sort="sortOf('minutes')"
          @sort="sortBy('minutes')"
        >
          Minutes
        </TableHead>
      </tr>
    </TableHeader>
    <TableBody>
      <TableRow v-for="row in rows" :key="row.member">
        <TableCell class="font-medium text-newt-text-primary">
          {{ row.member }}
        </TableCell>
        <TableCell>{{ row.action }}</TableCell>
        <TableCell align="end">{{ row.minutes }}</TableCell>
      </TableRow>
    </TableBody>
  </Table>
</template>

Installation

npx newtui@latest add tablenpx shadcn@latest add @newtui/tablenpx shadcn-vue@latest add @newtui/tablepnpm dlx newtui@latest add tablepnpm dlx shadcn@latest add @newtui/tablepnpm dlx shadcn-vue@latest add @newtui/tableyarn dlx newtui@latest add tableyarn dlx shadcn@latest add @newtui/tableyarn dlx shadcn-vue@latest add @newtui/tablebunx newtui@latest add tablebunx shadcn@latest add @newtui/tablebunx shadcn-vue@latest add @newtui/tabledeno run -A npm:newtui@latest add tabledeno run -A npm:shadcn@latest add @newtui/tabledeno run -A npm:shadcn-vue@latest add @newtui/tablevlx newtui@latest add tablevlx shadcn@latest add @newtui/tablevlx shadcn-vue@latest add @newtui/tablevp dlx newtui@latest add tablevp dlx shadcn@latest add @newtui/tablevp dlx shadcn-vue@latest add @newtui/tablenubx newtui@latest add tablenubx shadcn@latest add @newtui/tablenubx shadcn-vue@latest add @newtui/tablenlx newtui@latest add tablenlx shadcn@latest add @newtui/tablenlx shadcn-vue@latest add @newtui/tableupx newtui@latest add tableupx shadcn@latest add @newtui/tableupx shadcn-vue@latest add @newtui/table

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Copy the source into your project

import * as React from "react"

import { cn } from "@/lib/utils"

/*
 * A real `<table>`, so rows, columns and headers are announced as what they
 * are. The wrapper is what scrolls sideways on a narrow screen, which keeps
 * the table itself from pushing the page wide. `className` lands on the
 * table; the wrapper takes `wrapperClassName`.
 */
export interface TableProps extends React.ComponentProps<"table"> {
  wrapperClassName?: string
}

const Table = React.forwardRef<HTMLTableElement, TableProps>(
  ({ className, wrapperClassName, ...props }, ref) => (
    <div
      className={cn(
        "w-full overflow-x-auto rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-surface",
        wrapperClassName
      )}
    >
      <table
        ref={ref}
        className={cn(
          "w-full border-collapse text-sm leading-5 text-newt-text-secondary",
          className
        )}
        {...props}
      />
    </div>
  )
)
Table.displayName = "Table"

const TableHeader = React.forwardRef<
  HTMLTableSectionElement,
  React.ComponentProps<"thead">
>((props, ref) => <thead ref={ref} {...props} />)
TableHeader.displayName = "TableHeader"

const TableBody = React.forwardRef<
  HTMLTableSectionElement,
  React.ComponentProps<"tbody">
>(({ className, ...props }, ref) => (
  <tbody
    ref={ref}
    className={cn(
      "[&>tr:hover]:bg-newt-bg-hover [&>tr:not(:first-child)>td]:border-t [&>tr:not(:first-child)>td]:border-newt-border",
      className
    )}
    {...props}
  />
))
TableBody.displayName = "TableBody"

export interface TableRowProps extends React.ComponentProps<"tr"> {
  /** Marks the row as chosen, for a table whose rows can be picked. */
  selected?: boolean
}

const TableRow = React.forwardRef<HTMLTableRowElement, TableRowProps>(
  ({ className, selected, ...props }, ref) => (
    <tr
      ref={ref}
      aria-selected={selected}
      className={cn(
        "aria-selected:bg-newt-bg-active aria-selected:text-newt-text-primary",
        className
      )}
      {...props}
    />
  )
)
TableRow.displayName = "TableRow"

/** Which way a column is sorted. `none` means sortable, not sorted by. */
export type TableSort = "ascending" | "descending" | "none"

export interface TableHeadProps extends Omit<
  React.ComponentProps<"th">,
  "align"
> {
  /** `end` aligns the column to the inline end, for numbers. */
  align?: "start" | "end"
  /** Makes the heading a button and states the column's sort order. */
  sort?: TableSort
  /** Called when the sortable heading is activated. */
  onSort?: () => void
}

const TableHead = React.forwardRef<HTMLTableCellElement, TableHeadProps>(
  (
    {
      className,
      align = "start",
      sort,
      onSort,
      scope = "col",
      children,
      ...props
    },
    ref
  ) => (
    <th
      ref={ref}
      scope={scope}
      aria-sort={sort}
      className={cn(
        "whitespace-nowrap border-b border-newt-border bg-newt-bg-elevated px-4 py-2.5 text-xs font-bold uppercase tracking-[0.02em] text-newt-text-muted",
        align === "end" ? "text-end" : "text-start",
        className
      )}
      {...props}
    >
      {sort === undefined ? (
        children
      ) : (
        <button
          type="button"
          onClick={onSort}
          className={cn(
            "-mx-1.5 -my-1 inline-flex items-center gap-1 rounded-[var(--newt-radius-sm)] px-1.5 py-1 uppercase tracking-[inherit] hover:text-newt-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-newt-text-link",
            sort !== "none" && "text-newt-text-primary"
          )}
        >
          {children}
          <svg
            viewBox="0 0 16 16"
            aria-hidden="true"
            className={cn(
              "h-3 w-3",
              sort === "none" && "opacity-0",
              sort === "descending" && "rotate-180"
            )}
          >
            <path
              fill="currentColor"
              d="M8 3.5a1 1 0 0 1 .7.3l3.5 3.5a1 1 0 0 1-1.4 1.4L8 5.9 5.2 8.7a1 1 0 0 1-1.4-1.4l3.5-3.5a1 1 0 0 1 .7-.3Z"
            />
          </svg>
        </button>
      )}
    </th>
  )
)
TableHead.displayName = "TableHead"

export interface TableCellProps extends Omit<
  React.ComponentProps<"td">,
  "align"
> {
  /** `end` aligns the cell to the inline end and sets tabular figures. */
  align?: "start" | "end"
}

const TableCell = React.forwardRef<HTMLTableCellElement, TableCellProps>(
  ({ className, align = "start", ...props }, ref) => (
    <td
      ref={ref}
      className={cn(
        "whitespace-nowrap px-4 py-2.5",
        align === "end" ? "text-end tabular-nums" : "text-start",
        className
      )}
      {...props}
    />
  )
)
TableCell.displayName = "TableCell"

const TableCaption = React.forwardRef<
  HTMLTableCaptionElement,
  React.ComponentProps<"caption">
>(({ className, ...props }, ref) => (
  <caption
    ref={ref}
    className={cn(
      "caption-bottom border-t border-newt-border px-4 py-2.5 text-start text-xs text-newt-text-muted",
      className
    )}
    {...props}
  />
))
TableCaption.displayName = "TableCaption"

export {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  TableCaption,
}
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

/*
 * A real `<table>`, so rows, columns and headers are announced as what they
 * are. The wrapper is what scrolls sideways on a narrow screen, which keeps
 * the table itself from pushing the page wide. `class` and other attributes
 * land on the table; the wrapper takes `wrapperClass`.
 */
defineOptions({ inheritAttrs: false })

const props = defineProps<{
  class?: HTMLAttributes["class"]
  wrapperClass?: HTMLAttributes["class"]
}>()
</script>

<template>
  <div
    :class="
      cn(
        'w-full overflow-x-auto rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-surface',
        props.wrapperClass
      )
    "
  >
    <table
      v-bind="$attrs"
      :class="
        cn(
          'w-full border-collapse text-sm leading-5 text-newt-text-secondary',
          props.class
        )
      "
    >
      <slot />
    </table>
  </div>
</template>
<template>
  <thead>
    <slot />
  </thead>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = defineProps<{ class?: HTMLAttributes["class"] }>()
</script>

<template>
  <tbody
    :class="
      cn(
        '[&>tr:hover]:bg-newt-bg-hover [&>tr:not(:first-child)>td]:border-t [&>tr:not(:first-child)>td]:border-newt-border',
        props.class
      )
    "
  >
    <slot />
  </tbody>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    /** Marks the row as chosen, for a table whose rows can be picked. */
    selected?: boolean
  }>(),
  { selected: undefined }
)
</script>

<template>
  <tr
    :aria-selected="props.selected"
    :class="
      cn(
        'aria-selected:bg-newt-bg-active aria-selected:text-newt-text-primary',
        props.class
      )
    "
  >
    <slot />
  </tr>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

import type { TableSort } from "."

const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    /** `end` aligns the column to the inline end, for numbers. */
    align?: "start" | "end"
    /** Makes the heading a button and states the column's sort order. */
    sort?: TableSort
    scope?: "col" | "row"
  }>(),
  { align: "start", scope: "col" }
)

const emit = defineEmits<{
  /** Fired when the sortable heading is activated. */
  (e: "sort"): void
}>()
</script>

<template>
  <th
    :scope="props.scope"
    :aria-sort="props.sort"
    :class="
      cn(
        'whitespace-nowrap border-b border-newt-border bg-newt-bg-elevated px-4 py-2.5 text-xs font-bold uppercase tracking-[0.02em] text-newt-text-muted',
        props.align === 'end' ? 'text-end' : 'text-start',
        props.class
      )
    "
  >
    <slot v-if="props.sort === undefined" />
    <button
      v-else
      type="button"
      :class="
        cn(
          '-mx-1.5 -my-1 inline-flex items-center gap-1 rounded-[var(--newt-radius-sm)] px-1.5 py-1 uppercase tracking-[inherit] hover:text-newt-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-newt-text-link',
          props.sort !== 'none' && 'text-newt-text-primary'
        )
      "
      @click="emit('sort')"
    >
      <slot />
      <svg
        viewBox="0 0 16 16"
        aria-hidden="true"
        :class="
          cn(
            'h-3 w-3',
            props.sort === 'none' && 'opacity-0',
            props.sort === 'descending' && 'rotate-180'
          )
        "
      >
        <path
          fill="currentColor"
          d="M8 3.5a1 1 0 0 1 .7.3l3.5 3.5a1 1 0 0 1-1.4 1.4L8 5.9 5.2 8.7a1 1 0 0 1-1.4-1.4l3.5-3.5a1 1 0 0 1 .7-.3Z"
        />
      </svg>
    </button>
  </th>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    /** `end` aligns the cell to the inline end and sets tabular figures. */
    align?: "start" | "end"
  }>(),
  { align: "start" }
)
</script>

<template>
  <td
    :class="
      cn(
        'whitespace-nowrap px-4 py-2.5',
        props.align === 'end' ? 'text-end tabular-nums' : 'text-start',
        props.class
      )
    "
  >
    <slot />
  </td>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = defineProps<{ class?: HTMLAttributes["class"] }>()
</script>

<template>
  <caption
    :class="
      cn(
        'caption-bottom border-t border-newt-border px-4 py-2.5 text-start text-xs text-newt-text-muted',
        props.class
      )
    "
  >
    <slot />
  </caption>
</template>
export { default as Table } from "./Table.vue"
export { default as TableHeader } from "./TableHeader.vue"
export { default as TableBody } from "./TableBody.vue"
export { default as TableRow } from "./TableRow.vue"
export { default as TableHead } from "./TableHead.vue"
export { default as TableCell } from "./TableCell.vue"
export { default as TableCaption } from "./TableCaption.vue"

/** Which way a column is sorted. `none` means sortable, not sorted by. */
export type TableSort = "ascending" | "descending" | "none"

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Table to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Table to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { Table } from "@/components/ui/table"

export function Example() {
  return <Table />
}
<script setup lang="ts">
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell, TableCaption } from "@/components/ui/table"
</script>

<template>
  <Table />
</template>

API reference

Table

PropType
wrapperClassName / wrapperClass?string

Classes for the scrolling wrapper, which is where a width or a max-height belongs.

Typestring

TableHead

PropType
sort?"ascending" | "descending" | "none"

Makes the heading a button and sets `aria-sort`. `none` is a sortable column the table is not currently sorted by.

Type"ascending" | "descending" | "none"
onSort / @sort?() => void

Called when the sortable heading is activated.

Type() => void
align?"start" | "end"

`end` aligns the heading with a column of numbers.

Type"start" | "end"
Default"start"
scope?"col" | "row"

Which cells the heading labels.

Type"col" | "row"
Default"col"

TableCell

PropType
align?"start" | "end"

`end` right-aligns the cell in left-to-right text and sets tabular figures.

Type"start" | "end"
Default"start"

TableRow

PropType
selected?boolean

Marks the row as chosen and sets `aria-selected`.

Typeboolean

TableHeader, TableBody and TableCaption render <thead>, <tbody> and <caption>. Put a plain <tr> inside the header; TableRow is for body rows.

Accessibility

Because it is a real table, a screen reader announces the column heading with each cell and lets the reader move by row and column. Every TableHead has a scope. Give the table a TableCaption, which names it, or an aria-label. A sortable heading is a button inside the <th>, and the <th> carries aria-sort, so the current order is announced and not only shown by the arrow. On a narrow screen the wrapper scrolls sideways and the cells do not wrap.

Tokens

Table reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-table.

  • --newt-border
  • --newt-radius-md
  • --newt-bg-surface
  • --newt-text-secondary
  • --newt-text-muted
  • --newt-bg-elevated
  • --newt-bg-hover
  • --newt-bg-active
  • --newt-text-primary
  • --newt-radius-sm
  • --newt-text-link