new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

shadcn/ui · Components · all subjects

component usage & composition

23 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Example Card component composition tree

Card component has the following composition structure: Card contains CardHeader (which contains CardTitle, CardDescription, and CardAction), CardContent, and CardFooter.

LLMs and coding agents compose elements more reliably with composition documentation

When LLMs and coding agents can see the full component structure in composition sections, they compose elements more reliably, resulting in fewer missing wrappers, fewer wrong hierarchies, and better matches to examples.

Data Table project structure

The recommended file structure for a data table is: app/payments/columns.tsx (client component with column definitions), app/payments/data-table-features.ts (shared features object), app/payments/data-table.tsx (client component with DataTable component), and app/payments/page.tsx (server component for data fetching and rendering).

TanStack Table v9 feature-based architecture

TanStack Table v9 is feature-based: you opt into behavior by declaring it with tableFeatures(). Anything not listed is tree-shaken out. You must declare features like columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, and rowSortingFeature. Register filter functions under filterFns and sort functions under sortFns. The core row model is always included and never registered manually.

Data Table features configuration example

Example of setting up data table features: ```tsx import { columnFilteringFeature, columnVisibilityFeature, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, } from "@tanstack/react-table" export const features = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) export type DataTableFeatures = typeof features ``` This features object should be passed as the first generic argument to ColumnDef, Column, Table, and Row so each type knows which feature APIs are available.

Column definitions with createColumnHelper

Use createColumnHelper<DataTableFeatures, Payment>() to define columns. Use columnHelper.accessor() for data columns and columnHelper.display() for columns without data. Pass DataTableFeatures as the first generic to enable all feature APIs.

Basic column definition example

```tsx "use client" import { createColumnHelper } from "@tanstack/react-table" import { type DataTableFeatures } from "./data-table-features" export type Payment = { id: string amount: number status: "pending" | "processing" | "success" | "failed" email: string } const columnHelper = createColumnHelper<DataTableFeatures, Payment>() export const columns = columnHelper.columns([ columnHelper.accessor("status", { header: "Status", }), columnHelper.accessor("email", { header: "Email", }), columnHelper.accessor("amount", { header: "Amount", }), ]) ```

DataTable component implementation

```tsx "use client" import { useTable, type ColumnDef, type RowData } from "@tanstack/react-table" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" import { features, type DataTableFeatures } from "./data-table-features" interface DataTableProps<TData extends RowData> { columns: ColumnDef<DataTableFeatures, TData>[] data: TData[] } export function DataTable<TData extends RowData>({ columns, data, }: DataTableProps<TData>) { const table = useTable({ features, data, columns, }) return ( <div className="overflow-hidden rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id}> {header.isPlaceholder ? null : ( <table.FlexRender header={header} /> )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id}> <table.FlexRender cell={cell} /> </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center"> No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> ) } ```

FlexRender usage in TanStack Table v9

TanStack Table v9 provides <table.FlexRender header={header} /> and <table.FlexRender cell={cell} /> components directly on the table instance with no extra import needed. The classic flexRender(component, context) helper function from v8 still works as an alternative.

Cell formatting with currency example

```tsx columnHelper.accessor("amount", { header: () => <div className="text-right">Amount</div>, cell: ({ row }) => { const amount = parseFloat(row.getValue("amount")) const formatted = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }).format(amount) return <div className="text-right font-medium">{formatted}</div> }, }) ```

Row actions with DropdownMenu

```tsx columnHelper.display({ id: "actions", cell: ({ row }) => { const payment = row.original return ( <DropdownMenu> <DropdownMenuTrigger render={<Button variant="ghost" className="h-8 w-8 p-0" />} > <span className="sr-only">Open menu</span> <MoreHorizontal className="h-4 w-4" /> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuItem onClick={() => navigator.clipboard.writeText(payment.id)} > Copy payment ID </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem>View customer</DropdownMenuItem> <DropdownMenuItem>View payment details</DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) }, }) ``` Access row data using row.original to handle actions for the row, such as using the id to make API calls.

Pagination with TanStack Table v9

Pagination is automatically enabled when rowPaginationFeature and createPaginatedRowModel() are included in the features object. The table automatically paginates rows into pages of 10 by default. No additional configuration is needed in useTable to enable pagination.

Pagination controls implementation

```tsx import { Button } from "@/components/ui/button" export function DataTable<TData extends RowData>({ columns, data, }: DataTableProps<TData>) { const table = useTable({ features, data, columns, }) return ( <div> <div className="overflow-hidden rounded-md border"> <Table>{ /* ... */ }</Table> </div> <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> </div> ) } ```

Sorting implementation with TanStack Table v9

```tsx "use client" import * as React from "react" import { useTable, type ColumnDef, type RowData, type SortingState, } from "@tanstack/react-table" export function DataTable<TData extends RowData>({ columns, data, }: DataTableProps<TData>) { const [sorting, setSorting] = React.useState<SortingState>([]) const table = useTable({ features, data, columns, onSortingChange: setSorting, state: { sorting, }, }) return ( <div> <div className="overflow-hidden rounded-md border"> <Table>{ /* ... */ }</Table> </div> </div> ) } ``` The rowSortingFeature and sorted row model are already registered in the features object. Wire up the sorting state using onSortingChange and the state option.

Sortable header cell example

```tsx columnHelper.accessor("email", { header: ({ column }) => { return ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Email <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ) }, }) ``` Calling column.toggleSorting() with a boolean automatically sorts the table in ascending and descending order when the header cell is clicked.

Column filtering implementation

```tsx "use client" import * as React from "react" import { useTable, type ColumnDef, type ColumnFiltersState, type RowData, type SortingState, } from "@tanstack/react-table" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" export function DataTable<TData extends RowData>({ columns, data, }: DataTableProps<TData>) { const [sorting, setSorting] = React.useState<SortingState>([]) const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]) const table = useTable({ features, data, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, state: { sorting, columnFilters, }, }) return ( <div> <div className="flex items-center py-4"> <Input placeholder="Filter emails..." value={(table.getColumn("email")?.getFilterValue() as string) ?? ""} onChange={(event) => table.getColumn("email")?.setFilterValue(event.target.value) } className="max-w-sm" /> </div> <div className="overflow-hidden rounded-md border"> <Table>{ /* ... */ }</Table> </div> </div> ) } ``` The columnFilteringFeature and filtered row model are already part of the features object. Wire up the filter state using onColumnFiltersChange and render an input to set filter values.

Column visibility toggle implementation

```tsx "use client" import * as React from "react" import { useTable, type ColumnDef, type ColumnFiltersState, type ColumnVisibilityState, type RowData, type SortingState, } from "@tanstack/react-table" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" export function DataTable<TData extends RowData>({ columns, data, }: DataTableProps<TData>) { const [sorting, setSorting] = React.useState<SortingState>([]) const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]) const [columnVisibility, setColumnVisibility] = React.useState<ColumnVisibilityState>({}) const table = useTable({ features, data, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, state: { sorting, columnFilters, columnVisibility, }, }) return ( <div> <div className="flex items-center py-4"> <Input placeholder="Filter emails..." value={(table.getColumn("email")?.getFilterValue() as string) ?? ""} onChange={(event) => table.getColumn("email")?.setFilterValue(event.target.value) } className="max-w-sm" /> <DropdownMenu> <DropdownMenuTrigger render={<Button variant="outline" className="ml-auto" />}> Columns </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="overflow-hidden rounded-md border"> <Table>{ /* ... */ }</Table> </div> </div> ) } ``` Use onColumnVisibilityChange and ColumnVisibilityState to manage column visibility. Add a dropdown menu to toggle columns using column.toggleVisibility().

Row selection implementation

```tsx // In columns.tsx columnHelper.display({ id: "select", header: ({ table }) => ( <Checkbox checked={table.getIsAllPageRowsSelected()} indeterminate={ table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected() } onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} aria-label="Select all" /> ), cell: ({ row }) => ( <Checkbox checked={row.getIsSelected()} onCheckedChange={(value) => row.toggleSelected(!!value)} aria-label="Select row" /> ), enableSorting: false, enableHiding: false, }) // In data-table.tsx const [rowSelection, setRowSelection] = React.useState({}) const table = useTable({ features, data, columns, onRowSelectionChange: setRowSelection, state: { rowSelection, }, }) ``` Add a selection column using columnHelper.display() with Checkbox components for header and cells. Wire up with onRowSelectionChange.

Display selected rows count

Use table.getFilteredSelectedRowModel().rows.length to get the number of selected rows. Example: `{table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s) selected.`

Data Table philosophy

Every data table is unique with specific sorting, filtering, and data source requirements. Rather than combining all variations into a single component, data tables should be built custom using TanStack Table as a headless UI library that provides flexibility. Tables can be extracted into reusable components if needed.

Data Table installation command

To install the Table component for data tables, run: npx shadcn@latest add table

Data Table RTL support

To enable RTL support in shadcn/ui for data tables, see the RTL configuration guide.

TanStack Table v9 dependency installation

Add the @tanstack/react-table dependency with: npm install @tanstack/react-table. This guide uses TanStack Table v9.

Give your agent this brain