From b188e8573df216b2538a612a3ed87e55aeebe913 Mon Sep 17 00:00:00 2001 From: Mathis Date: Thu, 20 Jun 2024 15:02:44 +0200 Subject: [PATCH] feat(component): add DataTable component This commit introduces a new DataTable component in the UI component library. It includes features like column sorting, pagination, and customizable filtering. This reusable component is designed to handle and display data tables across different parts of the application. --- src/components/ui/data-table.tsx | 133 +++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 src/components/ui/data-table.tsx diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx new file mode 100644 index 0000000..5c84542 --- /dev/null +++ b/src/components/ui/data-table.tsx @@ -0,0 +1,133 @@ +"use client" + +import { + type ColumnDef, + flexRender, + getCoreRowModel, + getPaginationRowModel, + type ColumnFiltersState, + getFilteredRowModel, + getSortedRowModel, type SortingState, + useReactTable, +} from "@tanstack/react-table"; + +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" +import {Button} from "@/components/ui/button"; +import {useState} from "react"; +import {Input} from "@/components/ui/input"; + +interface DataTableProps { + columns: ColumnDef[] + data: TData[] + fieldToFilter: string +} + +export function DataTable({ + columns, + data, + fieldToFilter, + }: DataTableProps) { + const [sorting, setSorting] = useState([]) + const [columnFilters, setColumnFilters] = useState( + [] + ) + + const table = useReactTable({ + data, + columns, + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + onSortingChange: setSorting, + getSortedRowModel: getSortedRowModel(), + onColumnFiltersChange: setColumnFilters, + getFilteredRowModel: getFilteredRowModel(), + state: { + sorting, + columnFilters, + }, + }) + + return ( +
+
+ + table.getColumn(fieldToFilter)?.setFilterValue(event.target.value) + } + className="max-w-sm" + /> +
+
+ + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => { + return ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ) + })} + + ))} + + + {table.getRowModel().rows?.length ? ( + table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => ( + + {flexRender(cell.column.columnDef.cell, cell.getContext())} + + ))} + + )) + ) : ( + + + No results. + + + )} + +
+
+
+ + +
+
+ ) +}