Column layout example
Save column widths, order, pins, and hidden columns with onColumnLayoutChange and restore them with defaultColumnLayout.
defaultColumnLayout seeds the widths, order, pins, and hidden columns once at mount. onColumnLayoutChange reports the layout after each change. The demo saves the layout to localStorage. Resize a header, drag a column, or hide one, then reload the page to see the grid restore the layout.
Resize a header edge, drag a header, or pin/hide a column (header menu / columns menu) — every change persists and is restored on the next reload. Current order: (defaults or saved)
pnpm dlx shadcn@latest add @gridcn/data-grid-column-layout-demo
What the demo shows
defaultColumnLayout={readLayout}passes a function. The grid calls it once on the client after mount, before the first paint, so the server renders the default layout and never readslocalStorage. The grid ignores later changes to this prop.onColumnLayoutChange={persist}runs once for each committed change: a resize release, a reorder drop, a pin or unpin, and a hide or show. It does not run for each drag frame.DataGridColumnsMenuhides and restores columns, which updateshidden.- Reset layout clears the saved layout and mounts the grid again with a new
key, because the grid readsdefaultColumnLayoutonce. - The text above the grid lists the
orderof the most recent snapshot.
The snapshot
onColumnLayoutChange receives the whole layout after each change. widths lists only the columns that the user resized. order lists every column id. pins maps a column id to "start" or "end", and hidden lists the hidden column ids. This grid saves the layout and restores it after mount:
"use client";
import {
DataGrid,
defineColumns,
type ColumnLayout,
} from "@/components/data-grid/data-grid";
type Person = { id: string; name: string; age: number };
const columns = defineColumns<Person>()([
{ id: "name", header: "Name", accessorKey: "name" },
{ id: "age", header: "Age", accessorKey: "age", type: "number" },
]);
const rows: Person[] = [{ id: "1", name: "Ada", age: 36 }];
const STORAGE_KEY = "people-grid-layout";
function readLayout(): ColumnLayout | undefined {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
return raw ? (JSON.parse(raw) as ColumnLayout) : undefined;
} catch {
return undefined;
}
}
function saveLayout(layout: ColumnLayout) {
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(layout));
} catch {
return;
}
}
export function PeopleGrid() {
return (
<DataGrid
defaultData={rows}
columns={columns}
className="h-60"
defaultColumnLayout={readLayout}
onColumnLayoutChange={saveLayout}
/>
);
}To reset without a remount, pass columnLayout with onColumnLayoutChange.
Related
- Save a column layout: the steps to save and restore a layout
- Saved views: name, save, and share a layout with the sort and filters
- Pinned columns example: the gestures that the snapshot records
- URL state: share a layout as a URL