Run bulk actions
Show a bar for the checked rows that updates, deletes, or exports them, with one undoable write for each button.
A bulk bar needs the checked row ids and one write for each button. Checkbox row markers fill the ids. On a click, the grid API reads them.
Before you start
- Give every row a stable
id, or passgetRowId. - Install
data-grid-iofor the export button. - Install the shadcn
sonnercomponent for the toast. - To make the writes undoable, mount the history plugin.
useDataGridStateis the short path, anduseDataGridHistoryworks withdefaultData. A grid without the plugin keeps no history.
Steps
- Set
rowMarkers="checkbox". A checked marker adds its row id toselection.rowIds, and a cell range does not. A checkbox marker makescheckedRowsLifetimedefault to'until-cleared', so a click on a cell keeps the checks. With'until-click', a click on a cell clears them. - Keep a count in
onSelectionChangeand show the bar while the count is above zero. - Hold the grid API in a ref and read
getSelection().rowIdsinside each click handler. - Write the checked rows with one action per button.
Wire the bar
onSelectionChange fires on every selection change, and a drag changes it at each step. The callback keeps only a count. The click handlers read the ids:
"use client";
import { useRef, useState } from "react";
import { toast } from "sonner";
import {
DataGrid,
defineColumns,
type DataGridApi,
} from "@/components/data-grid/data-grid";
import { useDataGridState } from "@/components/data-grid-history/data-grid-history";
import { exportGrid } from "@/components/data-grid-io/data-grid-io";
import { Button } from "@/components/ui/button";
type Order = { id: string; customer: string; status: string };
const columns = defineColumns<Order>()([
{ id: "customer", header: "Customer", accessorKey: "customer", type: "text" },
{ id: "status", header: "Status", accessorKey: "status", type: "text" },
]);
export function OrdersGrid({ initialOrders }: { initialOrders: Order[] }) {
const grid = useDataGridState(initialOrders);
const gridRef = useRef<DataGridApi<Order> | null>(null);
const [checkedCount, setCheckedCount] = useState(0);
const checkedIds = () => gridRef.current?.getSelection().rowIds ?? [];
const markShipped = () => {
const patches = checkedIds().map((rowId) => ({
rowId,
changes: { status: "shipped" },
}));
const { skipped } = gridRef.current?.actions.editRows(patches) ?? {
skipped: [],
};
if (skipped.length) toast(`${skipped.length} rows were not changed`);
};
const deleteChecked = () => {
gridRef.current?.actions.deleteRows([...checkedIds()]);
};
const exportChecked = () => {
const api = gridRef.current;
if (!api) return;
void exportGrid(api.store.getState(), { scope: "selection" });
};
return (
<>
{checkedCount > 0 && (
<div role="toolbar" aria-label="Bulk actions" className="flex gap-2">
<span>{checkedCount} checked</span>
<Button onClick={markShipped}>Mark shipped</Button>
<Button onClick={deleteChecked}>Delete</Button>
<Button onClick={exportChecked}>Export CSV</Button>
</div>
)}
<DataGrid
{...grid}
ref={gridRef}
columns={columns}
rowMarkers="checkbox"
checkedRowsLifetime="until-cleared"
onSelectionChange={(next) => setCheckedCount(next.rowIds.length)}
/>
</>
);
}One write for each button
editRows writes every row in one batch. onDataChange fires once, onSave fires once, and undo records one entry. The patched rows move to their sorted position at once.
editRows is updateRows with source: "edit" and reorder: "immediate". An updateRows call with source: "stream" stays off the undo stack and never reaches onSave.
editRows returns { applied, skipped, pending }. applied counts the cells it wrote. skipped lists each patch that did not land, with a reason such as "readonly" or "invalid". pending is true while an async validate holds the batch.
deleteRows deletes the rows in one batch and clears the selection, so the bar hides itself. If the grid has onBeforeDeleteRows, that callback can cancel the delete.
scope: "selection" exports the rows of the checked markers and the rows that a cell range covers. With a checkedRowsLifetime of 'until-cleared' or 'across-filters', the export writes only the checked rows while a row has a check.
In a server grid, rowIds holds only the checked rows that the grid has loaded. To act on checks from other pages or on all matching rows, send the value of useDataGridSelectedRows() to your server. See Select server rows.
Result
Checking a row marker shows the bar. In a local grid, each button changes, deletes, or exports all checked rows, and one undo step reverts the update or the delete.
Related
- Select server rows: act on checks across pages and on all matching rows.
- Selection model: the channels behind
rowIdsand cell ranges. - Row operations: the row actions behind
deleteRows. - Selection and cell events:
onSelectionChangeand itsgetRowIds()detail. - Save edits: send the bulk change to an API.