Skip to content

Instantly share code, notes, and snippets.

@mxkaske
Created August 2, 2024 19:45
Show Gist options
  • Save mxkaske/4f87a26bbba3486d2f2c0c83f60163eb to your computer and use it in GitHub Desktop.
Save mxkaske/4f87a26bbba3486d2f2c0c83f60163eb to your computer and use it in GitHub Desktop.
How extend shadcn data-table with tanstack table's meta object to fix cell width
"use client";
import type { ColumnDef } from "@tanstack/react-table";
export interface Schema {
region: string;
trend: string;
p50: number;
}
export const columns: ColumnDef<Schema>[] = [
{
accessorKey: "region",
header: "Region",
meta: {
headerClassName: "w-[100px]", // fixed width
},
},
{
accessorKey: "trend",
header: "Trend",
meta: {
headerClassName: "min-w-[300px] w-full", // min-width, taking
},
},
{
accessorKey: "p50",
header: "P50"
// dynamic width
},
];
"use client";
import type { ColumnDef, SortingState } from "@tanstack/react-table";
import {
flexRender,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import * as React from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@openstatus/ui";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const table = useReactTable({
data,
columns,
state: { sorting },
getCoreRowModel: getCoreRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
});
return (
<div className="rounded-md border">
<Table>
<TableHeader className="bg-muted/50">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => {
return (
<TableHead
key={header.id}
// REMINDER:
className={header.column.columnDef.meta?.headerClassName}
>
{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}
// REMINDER:
className={cell.column.columnDef.meta?.cellClassName}
>
{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>
);
}
import "@tanstack/react-table";
declare module "@tanstack/react-table" {
interface ColumnMeta {
headerClassName?: string;
cellClassName?: string;
}
}
@mxkaske
Copy link
Author

mxkaske commented Aug 2, 2024

See ColumnMeta docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment