데이터 테이블
관리자 패널, 대시보드 및 주문 목록을 위한 정렬 및 필터링이 가능하고 페이지 단위로 표시되는 테이블 — 네오브루탈리즘 스타일의 테두리와 그림자 효과가 적용되었습니다.
데이터 테이블은 완성된 컴포넌트가 아니라 가이드입니다. <Table /> 컴포넌트와, 정렬·필터링·페이지네이션·행 선택을 담당하는 헤드리스 엔진 TanStack Table을 조합해 직접 테이블을 구성합니다. 겉모습은 두꺼운 테두리, 선명한 그림자, 굵은 서체로 이루어진 네오브루탈리즘 공식이 맡습니다.
다음과 같은 경우에 사용합니다.
- 관리자 패널 — 정렬 가능한 열, 필터, 행별 동작 메뉴를 갖춘 주문, 사용자, 청구서 목록.
- 대시보드 — 서식이 적용된 셀, 상태 열, 페이지 단위로 불러오는 API 데이터를 다루는 결제나 활동 테이블.
- 일괄 작업 흐름 — 체크박스로 행을 선택해 여러 레코드를 한 번에 내보내거나 보관하거나 삭제합니다.
소개#
지금까지 내가 만든 데이터 테이블과 데이터그리드는 모두 저마다 달랐습니다. 각기 동작이 다르고, 정렬과 필터링 요구 사항이 고유하며, 다루는 데이터 소스도 제각각입니다.
이 모든 변형을 하나의 컴포넌트에 합치는 것은 합리적이지 않습니다. 그렇게 하면 헤드리스 UI가 제공하는 유연성을 잃게 됩니다.
그래서 data-table 컴포넌트를 제공하는 대신, 직접 만드는 방법을 안내하는 가이드를 제공하는 편이 더 도움이 되리라 생각했습니다.
기본 <Table /> 컴포넌트에서 시작해 복잡한 데이터 테이블을 처음부터 구축해 나가겠습니다.
팁: 앱의 여러 곳에서 같은 테이블을 사용하고 있다면, 언제든 재사용 가능한 컴포넌트로 추출할 수 있습니다.
목차#
이 가이드에서는 TanStack Table과 <Table /> 컴포넌트를 사용해 자신만의 커스텀 데이터 테이블을 구축하는 방법을 소개합니다. 다음 주제를 다룹니다.
설치#
<Table />컴포넌트를 프로젝트에 추가합니다.
pnpm dlx shadcn@latest add tablenpx shadcn@latest add tableyarn dlx shadcn@latest add tablebunx --bun shadcn@latest add table
tanstack/react-table의존성을 추가합니다.
pnpm add @tanstack/react-tablenpm install @tanstack/react-tableyarn add @tanstack/react-tablebun add @tanstack/react-table
사전 준비#
최근 결제 내역을 표시하는 테이블을 구축하겠습니다. 데이터는 다음과 같습니다.
type Payment = {
id: string
amount: number
status: "pending" | "processing" | "success" | "failed"
email: string
}
export const payments: Payment[] = [
{
id: "728ed52f",
amount: 100,
status: "pending",
email: "[email protected]",
},
{
id: "489e1d42",
amount: 125,
status: "processing",
email: "[email protected]",
},
// ...
]프로젝트 구조#
먼저 다음과 같은 파일 구조를 만듭니다.
app
└── payments
├── columns.tsx
├── data-table.tsx
└── page.tsx여기서는 Next.js 예제를 사용하지만, 다른 어떤 React 프레임워크에서도 동작합니다.
columns.tsx(클라이언트 컴포넌트) 에는 열 정의를 작성합니다.data-table.tsx(클라이언트 컴포넌트) 에는<DataTable />컴포넌트를 작성합니다.page.tsx(서버 컴포넌트) 는 데이터를 가져와 테이블을 렌더링하는 곳입니다.
기본 테이블#
먼저 기본 테이블을 구축해 보겠습니다.
열 정의#
먼저 열을 정의합니다.
"use client"
import { ColumnDef } from "@tanstack/react-table"
// This type is used to define the shape of our data.
// You can use a Zod schema here if you want.
export type Payment = {
id: string
amount: number
status: "pending" | "processing" | "success" | "failed"
email: string
}
export const columns: ColumnDef<Payment>[] = [
{
accessorKey: "status",
header: "Status",
},
{
accessorKey: "email",
header: "Email",
},
{
accessorKey: "amount",
header: "Amount",
},
]참고: 열은 테이블의 모양의 핵심을 정의하는 곳입니다. 표시할 데이터와, 그 데이터를 어떻게 서식 지정하고 정렬하고 필터링할지를 정의합니다.
<DataTable /> 컴포넌트#
다음으로 테이블을 렌더링할 <DataTable /> 컴포넌트를 만듭니다.
"use client"
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} 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 (
<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
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</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}>
{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>
</div>
)
}팁: <DataTable /> 을 여러 곳에서 사용하고 있다면, 이 컴포넌트를 components/ui/data-table.tsx 로 추출해 재사용 가능하게 만들 수 있습니다.
<DataTable columns={columns} data={data} />
테이블 렌더링#
마지막으로 페이지 컴포넌트 안에서 테이블을 렌더링합니다.
import { columns, Payment } from "./columns"
import { DataTable } from "./data-table"
async function getData(): Promise<Payment[]> {
// Fetch data from your API here.
return [
{
id: "728ed52f",
amount: 100,
status: "pending",
email: "[email protected]",
},
// ...
]
}
export default async function DemoPage() {
const data = await getData()
return (
<div className="container mx-auto py-10">
<DataTable columns={columns} data={data} />
</div>
)
}셀 서식 지정#
금액 셀을 달러 금액으로 표시하도록 서식을 지정해 보겠습니다. 아울러 셀을 오른쪽으로 정렬합니다.
열 정의 업데이트#
금액의 header 와 cell 정의를 다음과 같이 업데이트합니다.
export const columns: ColumnDef<Payment>[] = [
{
accessorKey: "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>
},
},
]같은 방법으로 다른 셀과 헤더의 서식도 지정할 수 있습니다.
행 작업#
테이블에 행 작업을 추가해 보겠습니다. 여기서는 <DropdownMenu /> 컴포넌트를 사용합니다.
열 정의 업데이트#
새 actions 열을 추가하기 위해 열 정의를 업데이트합니다. actions 셀은 <DropdownMenu /> 컴포넌트를 반환합니다.
"use client"
import { ColumnDef } from "@tanstack/react-table"
import { MoreHorizontal } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
export const columns: ColumnDef<Payment>[] = [
// ...
{
id: "actions",
cell: ({ row }) => {
const payment = row.original
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</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>
)
},
},
// ...
]cell 함수 안에서는 row.original 을 사용해 행 데이터에 접근할 수 있습니다. 이를 사용해 행 작업을 처리합니다. 예를 들어 id 를 사용해 API에 DELETE 요청을 보냅니다.
페이지네이션#
다음으로 테이블에 페이지네이션을 추가합니다.
<DataTable> 업데이트#
import {
ColumnDef,
flexRender,
getCoreRowModel,
getPaginationRowModel,
useReactTable,
} from "@tanstack/react-table"
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
})
// ...
}이렇게 하면 행이 자동으로 10건씩 페이지로 나뉩니다. 페이지 크기 커스터마이징과 수동 페이지네이션 구현에 대한 자세한 내용은 페이지네이션 문서를 참고하세요.
페이지네이션 컨트롤 추가#
<Button /> 컴포넌트와 table.previousPage(), table.nextPage() API 메서드를 사용해 테이블에 페이지네이션 컨트롤을 추가할 수 있습니다.
import { Button } from "@/components/ui/button"
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
})
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>
)
}더 고급 페이지네이션 컴포넌트에 대해서는 재사용 가능한 컴포넌트 섹션을 참고하세요.
정렬#
이메일 열을 정렬 가능하게 만들어 보겠습니다.
<DataTable> 업데이트#
"use client"
import * as React from "react"
import {
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table"
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([])
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
state: {
sorting,
},
})
return (
<div>
<div className="overflow-hidden rounded-md border">
<Table>{ ... }</Table>
</div>
</div>
)
}헤더 셀을 정렬 가능하게 만들기#
이제 email 헤더 셀을 업데이트해 정렬 컨트롤을 추가할 수 있습니다.
"use client"
import { ColumnDef } from "@tanstack/react-table"
import { ArrowUpDown } from "lucide-react"
export const columns: ColumnDef<Payment>[] = [
{
accessorKey: "email",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
Email
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
},
]이렇게 하면 사용자가 헤더 셀에서 토글할 때 테이블이 자동으로 (오름차순, 내림차순으로) 정렬됩니다.
필터링#
테이블의 이메일을 필터링하는 검색 입력을 추가해 보겠습니다.
<DataTable> 업데이트#
"use client"
import * as React from "react"
import {
ColumnDef,
ColumnFiltersState,
SortingState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([])
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
)
const table = useReactTable({
data,
columns,
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
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>
)
}이제 email 열에서 필터링이 활성화되었습니다. 다른 열에도 필터를 추가할 수 있습니다. 필터 커스터마이징에 대한 자세한 내용은 필터링 문서를 참고하세요.
열 표시#
@tanstack/react-table 의 표시 API를 사용하면 열 표시 여부 전환을 아주 간단하게 추가할 수 있습니다.
<DataTable> 업데이트#
"use client"
import * as React from "react"
import {
ColumnDef,
ColumnFiltersState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([])
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
)
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({})
const table = useReactTable({
data,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
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 asChild>
<Button variant="outline" className="ml-auto">
Columns
</Button>
</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 client"
import { ColumnDef } from "@tanstack/react-table"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
export const columns: ColumnDef<Payment>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
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,
},
]<DataTable> 업데이트#
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([])
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
)
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({})
const [rowSelection, setRowSelection] = React.useState({})
const table = useReactTable({
data,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
},
})
return (
<div>
<div className="overflow-hidden rounded-md border">
<Table />
</div>
</div>
)
}이렇게 하면 각 행에 체크박스가 추가되고, 헤더에는 모든 행을 선택하는 체크박스가 추가됩니다.
선택된 행 표시#
table.getFilteredSelectedRowModel() API를 사용해 선택된 행의 수를 표시할 수 있습니다.
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>재사용 가능한 컴포넌트#
데이터 테이블 구축에 사용할 수 있는 컴포넌트를 몇 가지 소개합니다. 이들은 Tasks 데모에서 가져온 것입니다.
열 헤더#
임의의 열 헤더를 정렬 가능하고 숨길 수 있게 만듭니다.
import { type Column } from "@tanstack/react-table"
import { ArrowDown, ArrowUp, ChevronsUpDown, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/registry/base/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/registry/base/ui/dropdown-menu"
interface DataTableColumnHeaderProps<
TData,
TValue,
> extends React.HTMLAttributes<HTMLDivElement> {
column: Column<TData, TValue>
title: string
}
export function DataTableColumnHeader<TData, TValue>({
column,
title,
className,
}: DataTableColumnHeaderProps<TData, TValue>) {
if (!column.getCanSort()) {
return <div className={cn(className)}>{title}</div>
}
return (
<div className={cn("flex items-center gap-2", className)}>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8 data-popup-open:bg-accent"
/>
}
>
<span>{title}</span>
{column.getIsSorted() === "desc" ? (
<ArrowDown />
) : column.getIsSorted() === "asc" ? (
<ArrowUp />
) : (
<ChevronsUpDown />
)}
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem onClick={() => column.toggleSorting(false)}>
<ArrowUp />
Asc
</DropdownMenuItem>
<DropdownMenuItem onClick={() => column.toggleSorting(true)}>
<ArrowDown />
Desc
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => column.toggleVisibility(false)}>
<EyeOff />
Hide
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
export const columns = [
{
accessorKey: "email",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Email" />
),
},
]페이지네이션#
페이지 크기와 선택 건수를 포함한 페이지네이션 컨트롤을 테이블에 추가합니다.
import { type Table } from "@tanstack/react-table"
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from "lucide-react"
import { Button } from "@/registry/base/ui/button"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/registry/base/ui/select"
const pageSizeItems = [10, 20, 25, 30, 40, 50].map((pageSize) => ({
label: `${pageSize}`,
value: `${pageSize}`,
}))
interface DataTablePaginationProps<TData> {
table: Table<TData>
}
export function DataTablePagination<TData>({
table,
}: DataTablePaginationProps<TData>) {
return (
<div className="flex items-center justify-between px-2">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Rows per page</p>
<Select
items={pageSizeItems}
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
if (value !== null) {
table.setPageSize(Number(value))
}
}}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue />
</SelectTrigger>
<SelectContent side="top">
{pageSizeItems.map((item) => (
<SelectItem key={item.value} value={item.value}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="icon"
className="hidden size-8 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<ChevronsLeft />
</Button>
<Button
variant="outline"
size="icon"
className="size-8"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft />
</Button>
<Button
variant="outline"
size="icon"
className="size-8"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight />
</Button>
<Button
variant="outline"
size="icon"
className="hidden size-8 lg:flex"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<ChevronsRight />
</Button>
</div>
</div>
</div>
)
}
<DataTablePagination table={table} />열 표시 전환#
열의 표시 여부를 전환하는 컴포넌트입니다.
"use client"
import { type Table } from "@tanstack/react-table"
import { Settings2 } from "lucide-react"
import { Button } from "@/registry/base/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/registry/base/ui/dropdown-menu"
export function DataTableViewOptions<TData>({
table,
}: {
table: Table<TData>
}) {
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="outline"
size="sm"
className="ml-auto hidden h-8 lg:flex"
/>
}
>
<Settings2 />
View
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[150px]">
{/* GroupLabel (Base UI) needs a Group ancestor or it throws error #31. */}
<DropdownMenuGroup>
<DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
</DropdownMenuGroup>
<DropdownMenuSeparator />
{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>
)
}
<DataTableViewOptions table={table} />RTL#
Neobrutalism에서 RTL 지원을 활성화하는 방법은 RTL 설정 가이드를 참고하세요.
접근성#
TanStack Table은 헤드리스입니다. 마크업을 전혀 렌더링하지 않으므로 접근성은 이 가이드에 등장하는 요소에서 나옵니다. <Table /> 컴포넌트는 네이티브 <table>, <th>, <td> 요소를 출력하고, 이 요소들이 WAI-ARIA Table 패턴에 따라 스크린 리더에 행과 열의 맥락을 전달합니다. 직접 만들어 가면서 챙겨야 할 것은 두 가지입니다. 현재 정렬 중인 헤더에 aria-sort를 지정하는 것, 그리고 선택 체크박스의 aria-label과 아이콘만 있는 트리거의 sr-only 텍스트를 그대로 유지하는 것입니다(위 코드 조각은 두 가지를 모두 지키고 있습니다).
이 가이드의 모든 컨트롤은 네이티브 버튼, 체크박스, 입력 요소이므로 키보드 동작은 브라우저 기본값을 그대로 따릅니다.
| 키 | 동작 |
|---|---|
Tab / Shift + Tab | 필터 입력, 정렬 헤더, 행 메뉴, 페이지네이션 등 테이블 컨트롤 사이로 포커스 이동 |
Space / Enter | 포커스된 정렬 또는 페이지네이션 버튼 활성화 |
Space | 포커스된 행 또는 전체 선택 체크박스 전환 |