import { ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, PaginationState, useReactTable } from "@tanstack/react-table"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Button } from "../ui/button"; import { useEffect, useState } from "react"; import Show from "../Show"; import { useTranslation } from "react-i18next"; interface DataTableProps { columns: ColumnDef[]; data: TData[]; pageCount: number; onPageChange?: (pageIndex: number, pageSize?: number) => Promise; onRowClick?: (id: string) => void; withPagination?: boolean; fallback?: React.ReactNode; } export function DataTable({ columns, data, onPageChange, pageCount, onRowClick, withPagination, fallback, }: DataTableProps) { const [{ pageIndex, pageSize }, setPagination] = useState({ pageIndex: 0, pageSize: 10, }); const { t } = useTranslation(); const pagination = { pageIndex, pageSize, }; const table = useReactTable({ data, columns, pageCount: pageCount, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), state: { pagination, }, onPaginationChange: setPagination, manualPagination: true, }); useEffect(() => { onPageChange?.(pageIndex, pageSize); }, [pageIndex]); const handleRowClick = (id: string) => { onRowClick?.(id); }; return (
{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) => ( { e.stopPropagation(); handleRowClick(row.original.id); }} > {row.getVisibleCells().map((cell) => ( {flexRender(cell.column.columnDef.cell, cell.getContext())} ))} )) ) : ( {fallback ? fallback : t("common.text.nodata")} )}
{table.getCanPreviousPage() && ( )} {table.getCanNextPage && ( )}
); }