TanStack Table
Manages table state and row processing while the application builds the interface.
- Downloads / mo
- 136.5M
- Stars
- 28.6K
- Last release
- 9.3.1
- License
- MIT
Strengths
- Leaves markup to the application. Build the table interface with custom markup and a design system.
- Adds features individually. Register sorting, filtering, and pagination features only when needed.
Limitations
- Table interface needs implementation. Provide markup, styles, and interactive controls alongside the table logic.
Quickstart
'use client'; import React from 'react'; import { tableFeatures, useTable, type ColumnDef } from '@tanstack/react-table'; type Person = { firstName: string }; const data: Person[] = [{ firstName: 'Tanner' }]; const features = tableFeatures({}); const columns: ColumnDef<typeof features, Person>[] = [{ accessorKey: 'firstName', header: 'First name' }]; export default function PersonTable() { const table = useTable({ features, columns, data }); return ( <table><tbody> {table.getRowModel().rows.map((row) => ( <tr key={row.id}>{row.getAllCells().map((cell) => ( <td key={cell.id}><table.FlexRender cell={cell} /></td> ))}</tr> ))} </tbody></table> ); }
TanStack Table examples
export function DataTable({ data: initialData, }: { data: z.infer<typeof schema>[] }) { const [data, setData] = React.useState(() => initialData) const [rowSelection, setRowSelection] = React.useState({}) const [columnVisibility, setColumnVisibility] = React.useState<ColumnVisibilityState>({}) const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>( [] ) const [sorting, setSorting] = React.useState<SortingState>([]) const [pagination, setPagination] = React.useState({ pageIndex: 0, pageSize: 10, }) const sortableId = React.useId() const sensors = useSensors( useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}) ) const dataIds = React.useMemo<UniqueIdentifier[]>( () => data?.map(({ id }) => id) || [], [data] ) const table = useTable({ features, data, columns, state: { sorting, columnVisibility, rowSelection, columnFilters, pagination, }, getRowId: (row) => row.id.toString(), enableRowSelection: true, onRowSelectionChange: setRowSelection, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onPaginationChange: setPagination, }) function handleDragEnd(event: DragEndEvent) { const { active, over } = event if (active && over && active.id !== over.id) { setData((data) => { const oldIndex = dataIds.indexOf(active.id) const newIndex = dataIds.indexOf(over.id) return arrayMove(data, oldIndex, newIndex) }) } } return ( <Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6" > <div className="flex items-center justify-between px-4 lg:px-6"> <Label htmlFor="view-selector" className="sr-only"> View </Label> <Select defaultValue="outline"> <SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector" > <SelectValue placeholder="Select a view" /> </SelectTrigger> <SelectContent> <SelectItem value="outline">Outline</SelectItem> <SelectItem value="past-performance">Past Performance</SelectItem> <SelectItem value="key-personnel">Key Personnel</SelectItem> <SelectItem value="focus-documents">Focus Documents</SelectItem> </SelectContent> </Select> <TabsList className="hidden **:data-[slot=badge]:size-5 **:data-[slot=badge]:rounded-full **:data-[slot=badge]:bg-muted-foreground/30 **:data-[slot=badge]:px-1 @4xl/main:flex"> <TabsTrigger value="outline">Outline</TabsTrigger> <TabsTrigger value="past-performance"> Past Performance <Badge variant="secondary">3</Badge> </TabsTrigger> <TabsTrigger value="key-personnel"> Key Personnel <Badge variant="secondary">2</Badge> </TabsTrigger> <TabsTrigger value="focus-documents">Focus Documents</TabsTrigger> </TabsList> <div className="flex items-center gap-2"> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" size="sm"> <IconLayoutColumns /> <span className="hidden lg:inline">Customize Columns</span> <span className="lg:hidden">Columns</span> <IconChevronDown /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-56"> {table .getAllColumns() .filter( (column) => typeof column.accessorFn !== "undefined" && column.getCanHide() ) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> <Button variant="outline" size="sm"> <IconPlus /> <span className="hidden lg:inline">Add Section</span> </Button> </div> </div> <TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6" > <div className="overflow-hidden rounded-lg border"> <DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} onDragEnd={handleDragEnd} sensors={sensors} id={sortableId} > <Table> <TableHeader className="sticky top-0 z-10 bg-muted"> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id} colSpan={header.colSpan}> {header.isPlaceholder ? null : ( <FlexRender header={header} /> )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody className="**:data-[slot=table-cell]:first:w-8"> {table.getRowModel().rows?.length ? ( <SortableContext items={dataIds} strategy={verticalListSortingStrategy} > {table.getRowModel().rows.map((row) => ( <DraggableRow key={row.id} row={row} /> ))} </SortableContext> ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </DndContext> </div> <div className="flex items-center justify-between px-4"> <div className="hidden flex-1 text-sm text-muted-foreground lg:flex"> {table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected. </div> <div className="flex w-full items-center gap-8 lg:w-fit"> <div className="hidden items-center gap-2 lg:flex"> <Label htmlFor="rows-per-page" className="text-sm font-medium"> Rows per page </Label> <Select value={`${table.state.pagination.pageSize}`} onValueChange={(value) => { table.setPageSize(Number(value)) }} > <SelectTrigger size="sm" className="w-20" id="rows-per-page"> <SelectValue placeholder={table.state.pagination.pageSize} /> </SelectTrigger> <SelectContent side="top"> {[10, 20, 30, 40, 50].map((pageSize) => ( <SelectItem key={pageSize} value={`${pageSize}`}> {pageSize} </SelectItem> ))} </SelectContent> </Select> </div> <div className="flex w-fit items-center justify-center text-sm font-medium"> Page {table.state.pagination.pageIndex + 1} of{" "} {table.getPageCount()} </div> <div className="ml-auto flex items-center gap-2 lg:ml-0"> <Button variant="outline" className="hidden h-8 w-8 p-0 lg:flex" onClick={() => table.setPageIndex(0)} disabled={!table.getCanPreviousPage()} > <span className="sr-only">Go to first page</span> <IconChevronsLeft /> </Button> <Button variant="outline" className="size-8" size="icon" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} > <span className="sr-only">Go to previous page</span> <IconChevronLeft /> </Button> <Button variant="outline" className="size-8" size="icon" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} > <span className="sr-only">Go to next page</span> <IconChevronRight /> </Button> <Button variant="outline" className="hidden size-8 lg:flex" size="icon" onClick={() => table.setPageIndex(table.getPageCount() - 1)} disabled={!table.getCanNextPage()} > <span className="sr-only">Go to last page</span> <IconChevronsRight /> </Button> </div> </div> </div> </TabsContent> <TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6" > <div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div> </TabsContent> <TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6"> <div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div> </TabsContent> <TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6" > <div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div> </TabsContent> </Tabs> ) }