@grotevos/custom-datatable
v0.2.0
Published
A reusable React data table component built with TanStack Table and shadcn-style UI primitives.
Readme
custom-datatable
A reusable React data table package built on TanStack Table and shadcn-style UI primitives.
Install
npm install custom-datatable @tanstack/react-table react react-domThis package renders Tailwind/shadcn class names. In Tailwind v3 projects, include the package in your Tailwind content paths after installing it:
// tailwind.config.js
module.exports = {
content: [
"./src/**/*.{ts,tsx}",
"./node_modules/custom-datatable/dist/**/*.{js,mjs}",
],
};Your app should already have the usual shadcn CSS variables and Tailwind setup.
Usage
import type { ExtendedColumnDef } from "custom-datatable";
import { DataTableWrapper, RowActions } from "custom-datatable";
type User = {
id: number;
name: string;
email: string;
};
const columns: ExtendedColumnDef<User>[] = [
{
accessorKey: "name",
header: "Name",
className: "min-w-48",
},
{
accessorKey: "email",
header: "Email",
},
{
id: "actions",
cell: ({ row }) => (
<RowActions
row={row}
items={[
{
id: "edit",
label: "Edit",
onClick: (row) => console.log(row.original),
},
]}
/>
),
},
];
export function UsersTable({ users }: { users: User[] }) {
return (
<DataTableWrapper
columns={columns}
data={users}
control={{ pagination: "internal", sorting: "internal" }}
defaults={{ perPage: 10 }}
/>
);
}Persist Table State
Use usePersistedTableState when you want a table to remember its page, sorting, and global filter in localStorage.
import { DataTableWrapper, usePersistedTableState } from "custom-datatable";
export function UsersTable({ users }: { users: User[] }) {
const tableState = usePersistedTableState("users-table");
return (
<DataTableWrapper
columns={columns}
data={users}
control={{ pagination: "internal", sorting: "internal" }}
defaults={{
pageIndex: tableState.pageIndex + 1,
sort: tableState.sorting[0],
onPageChange: (page) => tableState.setPageIndex(page - 1),
onSortingChange: tableState.setSorting,
}}
tableOptions={{
state: {
globalFilter: tableState.globalFilter,
},
onGlobalFilterChange: tableState.setGlobalFilter,
}}
/>
);
}API
DataTablerenders the table from provided rows, columns, optional sorting state, optional pagination UI state, and optional TanStack table options.DataTableWrapperadds optional internal sorting and pagination.RowActionsrenders a dropdown action menu with optional confirmation dialogs.usePersistedTableStatestorespageIndex,sorting, andglobalFilterinlocalStorage.ExtendedColumnDefis a TanStackColumnDefwith optionalclassName,headerClassName, andcellClassNamefields.
Build
npm install
npm run buildPublish with:
npm publish