Skip to content

shadcn.io is an independent project built on shadcn/ui

Guides

Data Table

Build a React data table on TanStack Table v9 and our Table: columns, pagination, sorting, filters, column visibility, row selection and expandable rows.

On this page15 sections

There's no DataTable component, on purpose. Every data table sorts, filters and pages its own way, and one component with a prop for each would fit none of them. Instead, TanStack Table (opens in a new tab) keeps the state and works out which rows to show, and our Table draws them. You own the result: one file you change like any other.

Preview width

Eight payments, five to a page. Type in the filter to narrow the emails, click Email to sort, hide columns from the Columns menu, tick rows to select them, and open a row's menu to copy its payment ID. This guide builds it one feature at a time.

Install

bun add @tanstack/react-table

Then the components it draws with, each from its page, or in one command:

shadcn CLILocked
Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

How it fits together

TanStack Table is headless: it has no markup. You give it three things and render what it hands back:

You provideWhat it is
featuresThe features this table uses, from tableFeatures(): sorting, filtering, pagination… plus the row models and the sort and filter functions they need
columnsOne definition per column: which value it reads, its header, how its cell renders
dataYour rows, an array of objects

useTable returns the table. table.getHeaderGroups() gives the header cells, table.getRowModel().rows the rows to show after sorting, filtering and paging, and table.FlexRender renders a header or a cell from its column definition. You map those into TableHeader, TableRow, TableHead and TableCell.

In Next.js, the table is a Client Component: TanStack Table keeps its state in the browser. Fetch the rows in a Server Component and pass them down as a prop.

A basic table

Define the columns

Start with the row type and a column helper. createColumnHelper takes the features and the row type, so every column is typed against both:

components/payments-table.tsx
"use client";

import {
  createColumnHelper,
  tableFeatures,
  useTable,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

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

const features = tableFeatures({});

const currency = new Intl.NumberFormat("en-US", {
  currency: "USD",
  style: "currency",
});

const helper = createColumnHelper<typeof features, Payment>();

const columns = helper.columns([
  helper.accessor("status", {
    cell: ({ getValue }) => <div className="capitalize">{getValue()}</div>,
    header: "Status",
  }),
  helper.accessor("email", { header: "Email" }),
  helper.accessor("amount", {
    cell: ({ getValue }) => (
      <div className="text-end font-medium">{currency.format(getValue())}</div>
    ),
    header: () => <div className="text-end">Amount</div>,
  }),
]);

helper.accessor reads a key of the row, and getValue() in its cell is typed from it: a number for amount, which Intl.NumberFormat turns into dollars. A header is a string or a function that returns markup. text-end rather than text-right keeps the numbers on the trailing edge in a right-to-left page too.

Keep features and columns outside the component, as TanStack recommends for tableFeatures, so they're created once and not on every render.

Render the table

components/payments-table.tsx
export const PaymentsTable = (props: { data: Payment[] }) => {
  const table = useTable({ columns, data: props.data, features });
  const { rows } = table.getRowModel();

  return (
    <div className="rounded-md border">
      <Table>
        <TableHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <TableRow key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <TableHead key={header.id}>
                  {header.isPlaceholder ? null : (
                    <table.FlexRender header={header} />
                  )}
                </TableHead>
              ))}
            </TableRow>
          ))}
        </TableHeader>
        <TableBody>
          {rows.length > 0 ? (
            rows.map((row) => (
              <TableRow key={row.id}>
                {row.getAllCells().map((cell) => (
                  <TableCell key={cell.id}>
                    <table.FlexRender cell={cell} />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell className="h-24 text-center" colSpan={columns.length}>
                No results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};

The empty row spans every column, so a filter that matches nothing says so instead of collapsing the table.

Pass it the data

app/payments/page.tsx
import { PaymentsTable } from "@/components/payments-table";

export default async function Page() {
  const payments = await getPayments(); // Your data: a database query or an API call.
  return <PaymentsTable data={payments} />;
}

Each feature below adds an entry or two to features, a column option, and the control that drives it.

Pagination

Eight transactions, five to a page, with the page number on the left and Previous and Next on the right, each disabled at its end.

Register the feature and its row model, and set the page size in initialState:

import {
  createPaginatedRowModel,
  rowPaginationFeature,
  tableFeatures,
} from "@tanstack/react-table";

const features = tableFeatures({
  paginatedRowModel: createPaginatedRowModel(),
  rowPaginationFeature,
});

const initialState = { pagination: { pageIndex: 0, pageSize: 5 } };

const table = useTable({ columns, data, features, initialState });

table.getRowModel() now returns only the current page. Add the controls under the table:

<div className="flex items-center justify-between py-4">
  <div className="text-muted-foreground text-sm">
    Page {table.state.pagination.pageIndex + 1} of {table.getPageCount()}
  </div>
  <div className="flex items-center gap-2">
    <Button
      disabled={!table.getCanPreviousPage()}
      onClick={() => table.previousPage()}
      size="sm"
      variant="outline"
    >
      Previous
    </Button>
    <Button
      disabled={!table.getCanNextPage()}
      onClick={() => table.nextPage()}
      size="sm"
      variant="outline"
    >
      Next
    </Button>
  </div>
</div>

For numbered pages, table.getPageOptions() lists the zero-based page indexes and table.setPageIndex(index) jumps to one; the numeric pagination example draws them, and Pagination is the component for page links. table.setPageSize(size) changes the rows per page.

Sorting

Register the sorting feature, its row model, and the sort functions your columns use. The keys of sortFns become the names a column can ask for:

import {
  createSortedRowModel,
  rowSortingFeature,
  sortFn_alphanumeric,
  tableFeatures,
} from "@tanstack/react-table";

const features = tableFeatures({
  rowSortingFeature,
  sortedRowModel: createSortedRowModel(),
  sortFns: { alphanumeric: sortFn_alphanumeric },
});

Then make the header a button that toggles the column's sort:

helper.accessor("email", {
  header: ({ column }) => (
    <Button
      className="-ms-2"
      onClick={column.getToggleSortingHandler()}
      size="sm"
      variant="ghost"
    >
      Email
      <ArrowUpDownIcon aria-hidden="true" />
    </Button>
  ),
  sortFn: "alphanumeric",
}),

-ms-2 pulls the ghost button's padding back so the word lines up with the cells under it. Every column can sort once the feature is registered; set enableSorting: false on the ones that shouldn't. column.getIsSorted() returns "asc", "desc" or false: use it to swap the icon, and to tell screen readers the order with aria-sort on the header cell:

const ariaSort = (direction: false | "asc" | "desc") => {
  if (direction === "asc") return "ascending";
  if (direction === "desc") return "descending";
  return undefined;
};

<TableHead aria-sort={ariaSort(header.column.getIsSorted())} key={header.id}>

The other built-in sort functions include sortFn_text, sortFn_datetime and sortFn_basic, each registered the same way.

Filtering

Five users with two search fields above them: one filters by name, the other by email, and both apply at once.

Register the filtering feature, its row model and a filter function, then name the function on each column you filter:

import {
  columnFilteringFeature,
  createFilteredRowModel,
  filterFn_includesString,
  tableFeatures,
} from "@tanstack/react-table";

const features = tableFeatures({
  columnFilteringFeature,
  filteredRowModel: createFilteredRowModel(),
  filterFns: { includesString: filterFn_includesString },
});

helper.accessor("email", { filterFn: "includesString", header: "Email" }),

An Input drives it through the column:

const email = table.getColumn("email");

<Input
  aria-label="Filter emails"
  className="max-w-sm"
  onChange={(event) => email?.setFilterValue(event.target.value)}
  placeholder="Filter emails..."
  type="search"
  value={String(email?.getFilterValue() ?? "")}
/>

includesString lowercases both sides before it compares, and an empty filter is removed, so clearing the input shows every row again. filterFn_includesStringSensitive, filterFn_equalsString, filterFn_inNumberRange and filterFn_arrIncludes are some of the others. To search every column from one input, register globalFilteringFeature with the same row model, set globalFilterFn: "includesString" on the table, and call table.setGlobalFilter(value).

Column visibility

Four orders with six columns and a Columns menu: untick a column and it leaves the header and every row.

Register columnVisibilityFeature, then list the columns that can hide in a Dropdown Menu, each a checkbox item:

<DropdownMenu>
  <DropdownMenuTrigger render={<Button variant="outline" />}>
    Columns
    <ChevronDownIcon aria-hidden="true" data-icon="inline-end" />
  </DropdownMenuTrigger>
  <DropdownMenuContent align="end">
    {table
      .getAllColumns()
      .filter((column) => column.getCanHide())
      .map((column) => (
        <DropdownMenuCheckboxItem
          checked={column.getIsVisible()}
          className="capitalize"
          key={column.id}
          onCheckedChange={(checked) => column.toggleVisibility(checked)}
        >
          {column.id}
        </DropdownMenuCheckboxItem>
      ))}
  </DropdownMenuContent>
</DropdownMenu>

In the body, render row.getVisibleCells() instead of row.getAllCells(), and give the empty row colSpan={table.getVisibleLeafColumns().length}, so hidden columns drop out of both. Set enableHiding: false on a column that must stay, such as the selection checkboxes or the actions.

Row selection

Products with a checkbox on each row, a select-all box in the header, a sortable Name column, and a count of the selected rows under the table.

Register rowSelectionFeature and add a first column of Checkboxes with helper.display, a column that reads no value:

helper.display({
  cell: ({ row }) => (
    <Checkbox
      aria-label="Select row"
      checked={row.getIsSelected()}
      onCheckedChange={(checked) => row.toggleSelected(checked)}
    />
  ),
  header: ({ table }) => (
    <Checkbox
      aria-label="Select all"
      checked={table.getIsAllPageRowsSelected()}
      indeterminate={table.getIsSomePageRowsSelected()}
      onCheckedChange={(checked) => table.toggleAllPageRowsSelected(checked)}
    />
  ),
  id: "select",
}),

indeterminate puts the header box in its mixed state (aria-checked="mixed") while only some rows on the page are ticked. With sorting or visibility registered too, add enableSorting: false and enableHiding: false to the column. Mark the selected rows so TableRow shades them:

<TableRow
  data-state={row.getIsSelected() ? "selected" : undefined}
  key={row.id}
>

table.getSelectedRowModel().rows holds the selection: map it to row.original for a bulk action. table.getFilteredSelectedRowModel() counts only the selected rows that pass the current filters, as the demo at the top does. Rows are keyed by their index unless you pass getRowId: (row) => row.id to useTable; do that when the data can change under the selection, or a refetch selects different rows.

Row actions

A display column at the end, with a menu in each cell. row.original is the row's own object:

helper.display({
  cell: ({ row }) => (
    <DropdownMenu>
      <DropdownMenuTrigger
        render={<Button className="size-8" size="icon-md" variant="ghost" />}
      >
        <MoreHorizontalIcon aria-hidden="true" />
        <span className="sr-only">Open menu</span>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem
          onClick={() => navigator.clipboard.writeText(row.original.id)}
        >
          Copy payment ID
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem>View customer</DropdownMenuItem>
        <DropdownMenuItem>View payment details</DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  ),
  enableHiding: false,
  id: "actions",
}),
Preview width

The same menu in a plain Table: Edit, Duplicate, and Delete in the destructive color after a separator. While a row's menu is open, the row stays shaded: TableRow styles a row that holds an element with aria-expanded="true", which the trigger sets. Keep destructive items last and behind a separator, and confirm them with an Alert Dialog.

Expandable rows

Three projects, each with its tasks: the chevron opens a panel under the row that lists every task with its assignee and status.

Register the expanding feature and its row model, and tell the table which rows can open:

import {
  createExpandedRowModel,
  type Row,
  rowExpandingFeature,
  tableFeatures,
} from "@tanstack/react-table";

const features = tableFeatures({
  expandedRowModel: createExpandedRowModel(),
  rowExpandingFeature,
});

const getRowCanExpand = (row: Row<typeof features, Project>) =>
  Boolean(row.original.tasks?.length);

const table = useTable({ columns, data, features, getRowCanExpand });

The first column holds the toggle, a button that says what it does and whether it's open:

helper.display({
  cell: ({ row }) =>
    row.getCanExpand() ? (
      <Button
        aria-expanded={row.getIsExpanded()}
        aria-label={row.getIsExpanded() ? "Hide tasks" : "Show tasks"}
        onClick={row.getToggleExpandedHandler()}
        size="icon-sm"
        variant="ghost"
      >
        {row.getIsExpanded() ? (
          <ChevronDownIcon aria-hidden="true" />
        ) : (
          <ChevronRightIcon aria-hidden="true" className="rtl:rotate-180" />
        )}
      </Button>
    ) : null,
  header: () => <span className="sr-only">Expand</span>,
  id: "expander",
}),

In the body, render a second row after each open one, its single cell spanning the table:

{rows.map((row) => (
  <Fragment key={row.id}>
    <TableRow>
      {row.getAllCells().map((cell) => (
        <TableCell key={cell.id}>
          <table.FlexRender cell={cell} />
        </TableCell>
      ))}
    </TableRow>
    {row.getIsExpanded() && row.original.tasks ? (
      <TableRow className="hover:bg-transparent">
        <TableCell colSpan={columns.length}>
          <TaskList tasks={row.original.tasks} />
        </TableCell>
      </TableRow>
    ) : null}
  </Fragment>
))}

rtl:rotate-180 turns the closed chevron to point the reading direction in a right-to-left page. When the children are rows of the same type, pass getSubRows: (row) => row.children to useTable instead, and an expanded row's children follow it in getRowModel() as rows of their own.

Server-side data

The features above sort, filter and page the rows in the browser, which suits the few thousand rows you can load at once. For more, the server does the work: turn off the table's own processing with manual* options, hold the state yourself, and fetch a page whenever it changes.

import {
  type PaginationState,
  rowPaginationFeature,
  rowSortingFeature,
  type SortingState,
  tableFeatures,
  useTable,
} from "@tanstack/react-table";
import { useState } from "react";

const features = tableFeatures({ rowPaginationFeature, rowSortingFeature });

export const PaymentsTable = () => {
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sorting, setSorting] = useState<SortingState>([]);
  // Your data hook: it fetches one sorted page and the total row count.
  const { rows, total } = usePayments({ pagination, sorting });

  const table = useTable({
    columns,
    data: rows,
    features,
    manualPagination: true,
    manualSorting: true,
    onPaginationChange: setPagination,
    onSortingChange: setSorting,
    rowCount: total,
    state: { pagination, sorting },
  });
  // Render as before.
};

No row models are registered: with manualPagination and manualSorting, the table shows data as it arrives. rowCount lets getPageCount() and getCanNextPage() work out the last page. Filtering works the same way with manualFiltering, state.columnFilters and onColumnFiltersChange.

Right to left

Preview width

The invoice table in Arabic, with dir="rtl" on Table: the columns run from the right, and the amounts, set with text-end, sit on the left edge.

Write alignment and spacing with logical classes (text-end, ms-*, -ms-2, ps-*) instead of left and right, and they flip with the direction. Set dir on the page or a parent, and wrap the app in Direction's provider so menus and other popups follow it too.

Accessibility

  • Real table markup. Table renders table, thead, th and td, so screen readers announce the column header with each cell. Add a TableCaption to name the table.
  • Every control has a name. The row and header checkboxes take aria-label, filter inputs take aria-label, and icon-only buttons carry a sr-only label or an aria-label.
  • State is announced. The expand button sets aria-expanded, and a sortable header cell can set aria-sort, as shown in Sorting.
  • Wide tables scroll. Table sits in a container that scrolls sideways. Give Table tabIndex={0} and an aria-label and that container becomes a focusable, named region, so keyboard users can scroll it with the arrow keys.

Examples

The data table examples are 8 tables, each adding one feature to the basic table, including row actions, resizable columns and numbered pages. For tables people only read, the table examples are styled Tables with no TanStack Table at all.

FAQ

Is there a DataTable component in shadcn?

No, in shadcn/ui or here. A data table is your own component: TanStack Table for the state and the row logic, and Table with Checkbox, Dropdown Menu, Input and Button for the markup. Each table's sorting, filtering and paging differ, so you write the one you need from the steps on this page.

When do I need a data table instead of a plain Table?

When people work with the rows: sort, filter, select, hide columns or page through. If they only read them, map your rows into Table directly and skip TanStack Table; the table examples are built that way.

Why doesn't my TanStack Table v8 code work?

v9 replaced useReactTable and the get*RowModel options with useTable and a features object from tableFeatures(), where each feature, row model and sort or filter function is registered. Column definitions use createColumnHelper<typeof features, TData>(). useLegacyTable from @tanstack/react-table/legacy runs v8-style options while you migrate.

Why does clicking the header not sort the column?

Check that rowSortingFeature and sortedRowModel: createSortedRowModel() are both in tableFeatures(), that the header's button calls column.getToggleSortingHandler(), and that a sortFn named on the column is registered in sortFns. With manualSorting: true, the table expects your server to sort data.

How do I paginate, sort and filter on the server?

Set manualPagination, manualSorting and manualFiltering, hold pagination, sorting and columnFilters in React state, pass them as state with their on*Change callbacks, and refetch when they change. Pass the total as rowCount so the page count is right. Don't register the row models: the server already did that work.

How do I get the selected rows?

table.getSelectedRowModel().rows.map((row) => row.original) gives the selected objects. Pass getRowId: (row) => row.id to useTable so the selection is keyed by your ids rather than row indexes, which change when the data does.

Does it work with Radix UI, React Aria or Ark UI?

Yes. TanStack Table is the same on every library; the Checkbox, Dropdown Menu and Button follow the library you installed them from. On React Aria, Table is React Aria's own table, so selection, sorting and keyboard navigation between cells come from it.

Can I use the data table in a React Server Component?

Not the table itself: TanStack Table keeps its state in the browser, so the table is a Client Component. Fetch the rows in a Server Component and pass them as a prop, as the page in A basic table does.

How do I keep a wide data table from breaking the layout on phones?

Table already sits in a container that scrolls sideways, so the page doesn't. Give Table tabIndex={0} and an aria-label so keyboard users can focus the container and scroll it, and use column visibility to hide the least useful columns on small screens.