Sub topic 13
Building data tables with TanStack Table
This chapter assumes you can write React function components with hooks and basic TypeScript, and that you have run npx shadcn@latest add table so the shadcn/ui Table components exist in your project. You should also know what a headless component is, from the earlier chapter on headless components.
Why tables need a headless library
A data table has a lot of state. Which column is sorted? Which rows are selected? Which page is visible? Writing this by hand is tedious and easy to get wrong.
TanStack Table solves the state problem and leaves the markup alone. It is a headless library. It does not render a <table>, apply a class, or ship CSS. You give it data and column definitions. It gives you back header groups, rows, and cells that you render yourself.
That fits the shadcn/ui model. The library owns the logic, and the shadcn/ui Table components own the look. You join the two in a component that lives in your codebase.
The core pieces
Three inputs are required for a working table.
datais an array of objects, one per row.columnsis an array of column definitions that say how to read and display each field.getCoreRowModelis a function that produces the basic row model. You passgetCoreRowModel()once.
The hook useReactTable takes these and returns a table instance. The instance exposes methods such as getHeaderGroups() and getRowModel().
A column definition has an accessorKey that names a property on each row object. It also has a header and, optionally, a cell. Both can be a string or a function. The helper flexRender renders either form, so you always call it instead of printing the value directly.
import {
useReactTable,
getCoreRowModel,
flexRender,
type ColumnDef,
} from "@tanstack/react-table"
type User = { name: string; email: string }
const columns: ColumnDef<User>[] = [
{ accessorKey: "name", header: "Name" },
{ accessorKey: "email", header: "Email" },
]
export function UserTable({ data }: { data: User[] }) {
const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel() })
return (
<table>
<thead>
{table.getHeaderGroups().map((group) => (
<tr key={group.id}>
{group.headers.map((header) => (
<th key={header.id}>
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
)
}This version uses plain HTML elements. It works, but it has none of the project's styling. The next step swaps in the shadcn/ui components.
Swapping in shadcn/ui Table components
The add table command copies a table.tsx file into components/ui. It exports Table, TableHeader, TableBody, TableRow, TableHead, TableCell, and a few others. Each one renders the matching HTML element with Tailwind classes attached.
Replacing the elements is a one-to-one mapping.
| Plain element | shadcn/ui component |
|---|---|
| `table` | `Table` |
| `thead` | `TableHeader` |
| `tbody` | `TableBody` |
| `tr` | `TableRow` |
| `th` | `TableHead` |
| `td` | `TableCell` |
The logic does not change. Only the tags do. This is the practical payoff of a headless library: you can restyle the whole table without touching the state code.
A common arrangement is to make the table generic, so one component serves every data type.
import {
useReactTable,
getCoreRowModel,
flexRender,
type ColumnDef,
} from "@tanstack/react-table"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
}
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
})
return (
<Table>
<TableHeader>
{table.getHeaderGroups().map((group) => (
<TableRow key={group.id}>
{group.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
)
}Two details are worth noting. The isPlaceholder check skips header cells that exist only to fill space in grouped headers. The empty branch renders one cell that spans every column, so an empty table still looks intentional.
Adding sorting and pagination
Features are opt-in. Each one needs a row model function and, for controlled behavior, a piece of state. The row model functions are imported from the library. The state lives in useState.
import * as React from "react"
import {
useReactTable,
getCoreRowModel,
getSortedRowModel,
getPaginationRowModel,
type ColumnDef,
type SortingState,
} from "@tanstack/react-table"
export function useSortableTable<TData, TValue>(
data: TData[],
columns: ColumnDef<TData, TValue>[]
) {
const [sorting, setSorting] = React.useState<SortingState>([])
return useReactTable({
data,
columns,
state: { sorting },
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
})
}To let users sort, render a header that calls column.toggleSorting. The shadcn/ui Button works well here, using the variant options from the cva chapter. Put the button inside a column's header function.
import { type ColumnDef } from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
type User = { name: string; email: string }
export const columns: ColumnDef<User>[] = [
{
accessorKey: "name",
header: ({ column }) => (
<Button
variant="outline"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
Name
</Button>
),
},
{ accessorKey: "email", header: "Email" },
]For pagination, the table instance gives you previousPage(), nextPage(), getCanPreviousPage(), and getCanNextPage(). Wire them to two buttons and disable each when its getCan... method returns false.
<div className="flex items-center justify-end space-x-2 py-4">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>Common errors
- Columns or data recreated on every render. Defining
columnsordatainline inside a component makes a new array each render. TanStack Table then sees changed inputs and may re-render in a loop or lose state. Definecolumnsat module level, or wrap them inuseMemo. Do the same fordatawhen you build it from other values. - Missing row model function. If you set
state.sortingbut never passgetSortedRowModel, clicking the header changes state but the rows do not reorder. Each feature needs its own row model function. - Skipping
flexRender. Printingheader.column.columnDef.headerdirectly shows a function when the definition uses one. Always pass the definition and context toflexRender. - Unstable row keys.
row.iddefaults to the row index. If rows can be added, removed, or reordered, supplygetRowIdso selection and expansion state follow the record, not the position. - Wrong
colSpanin the empty row. If you hide columns,columns.lengthcan be larger than the visible count. Usetable.getVisibleLeafColumns().lengthwhen columns can be toggled.
Accessibility notes
The shadcn/ui Table components render real table, th, and td elements, so screen readers get table semantics for free. Keep that benefit.
- Do not replace table elements with
divelements unless you add the matching ARIA roles yourself. - A sort button should expose its state. Add
aria-sortto theTableHeadwhen a column is sorted, with the valueascendingordescending. - Icon-only buttons need an accessible name, either visible text or an
aria-label. - Keep pagination buttons as real
buttonelements so they are reachable by keyboard.
Exercises
Exercise
You add state: { sorting } and onSortingChange: setSorting to useReactTable. Clicking the sort button updates the sorting state, but the rows never change order. What is the most likely cause, and what is the fix?
Show answer
The table has no sorted row model. Import getSortedRowModel from @tanstack/react-table and pass getSortedRowModel: getSortedRowModel() to useReactTable. Without it, the state changes but nothing applies the sort to the rows.
Exercise
A teammate defines const columns = [...] inside the UserTable component body, and the table resets its sort state whenever the parent re-renders. Give two ways to fix it.
Show answer
Move the columns array outside the component to module level, or wrap it in React.useMemo with the right dependency array. Both keep the array reference stable between renders, so TanStack Table does not see changed input.
Exercise
Why is it safe to swap <td> for the shadcn/ui TableCell without changing any table logic, and which part of the code would you touch to change how the table looks?
Show answer
TanStack Table is headless. It manages state and produces rows and cells, and it never renders markup. The shadcn/ui TableCell only supplies markup and classes. To change the look, edit components/ui/table.tsx or the className props, and leave the useReactTable code alone.