Controlled State and CRUD
comins-grid-layout@0.3.0
Use useDashboardGrid when the dashboard must remain serializable and React-controlled. The hook initializes once from initialColumns and initialWidgets; later changes should go through its commands or a restored snapshot.
import { DashboardGrid, useDashboardGrid } from "comins-grid-layout";
export function EditableDashboard() { const dashboard = useDashboardGrid({ initialColumns: 12, initialWidgets: [], onLayoutMutation: (event) => { console.log(event.kind, event.widgetIds, event.snapshot); }, });
const addMetric = () => { const id = crypto.randomUUID(); dashboard.commands.addWidget({ id, title: "Metric", layout: { id, x: 0, y: 0, w: 3, h: 2 }, }); };
return ( <> <button type="button" onClick={addMetric}>Add metric</button> <DashboardGrid columns={dashboard.columns} widgets={dashboard.widgets} onLayoutCommit={dashboard.commands.applyLayoutSnapshot} renderWidget={(widget) => widget.title} /> </> );}Reuse one ID for both widget.id and widget.layout.id. Duplicate IDs and invalid insertion layouts are rejected by the pure insertion helper.
Command reference
Section titled “Command reference”addWidgetadds a widget using its supplied layout.insertWidgetAtinserts a palette or transferred widget against the target layout and target snapshot.updateWidgetpatches metadata, data, flags, or layout;updateWidgetLayoutpatches geometry only.removeWidgetremoves one identity;clearWidgetsremoves every widget.resizeWidget(id, { w, h })sets explicit dimensions within constraints;restoreWidgetrestores the first saved pre-resize geometry.maximizeWidgetandminimizeWidgetremain deprecated compatibility commands.applyLayoutSnapshotwrites a completed GridStack layout back to React state.refreshLayoutincrements the hook’srefreshVersionfor the componentrefreshKey.resetLayout,restoreLayout,serializeLayout, andserializeStateare covered in Persistence.setColumns,autoArrangeWidgets,fitWidgetsToColumns, andfitWidgetToColumnsare covered in Columns, Arrange, and Reset.
The root exports also include pure state helpers for reducers or non-React code. insertDashboardWidgetAtLayout returns an accepted/rejected result without mutating either input. serializeDashboardState creates a complete serializable snapshot. transferDashboardWidget is described in the transfer guide.
Do not use raw GridStack add/remove methods for React content. Raw engine CRUD changes only engine/DOM state and can be replaced by the next controlled render.
Playground: /examples/widget/manage.
In 0.2.3, the adapter applies controlled geometry as one layout while retaining widget DOM. Packing after removal or Float changes can correct the requested coordinates; connect onLayoutCommit to applyLayoutSnapshot so those corrections reach React state. The pure commands themselves do not measure browser geometry.