Act on the selected rows
Show a bar for the checked rows that deletes, updates, or exports them as one undoable step.
A bulk bar needs the checked rows and one write per button. Turn on the checkbox row markers (rowMarkers="checkbox"), show the bar while selection.rowIds is not empty, and read the ids when a button is clicked. The marker checkboxes fill rowIds. A cell range does not.
"use client";
function OrdersGrid() {
const gridRef = useRef<DataGridApi<Order> | null>(null);
const [data, setData] = useState<readonly Order[]>(initialOrders);
const [checkedCount, setCheckedCount] = useState(0);
const checkedIds = () => gridRef.current?.getSelection().rowIds ?? [];
return (
<>
{checkedCount > 0 && (
<BulkBar
count={checkedCount}
onShip={() => markShipped(gridRef, checkedIds())}
onDelete={() => deleteChecked(gridRef, checkedIds())}
onExport={() => exportChecked(gridRef)}
/>
)}
<DataGrid
ref={gridRef}
data={data}
columns={columns}
rowMarkers="checkbox"
onDataChange={setData}
onSelectionChange={(next) => setCheckedCount(next.rowIds.length)}
/>
</>
);
}onSelectionChange fires once per cell during a drag, so the callback keeps only a count. The ids are read on the click, when they are needed.
One write per button
updateRows writes all rows in one change. onDataChange fires once and undo records one entry. Pass source: "edit", because the default "stream" source stays out of the undo stack:
function markShipped(gridRef: RefObject<DataGridApi<Order> | null>, rowIds: readonly string[]) {
gridRef.current?.actions.updateRows(
rowIds.map((rowId) => ({ rowId, changes: { status: "shipped" } })),
{ source: "edit", reorder: "immediate" },
);
}deleteRowsById deletes the rows by id:
function deleteChecked(gridRef: RefObject<DataGridApi<Order> | null>, rowIds: readonly string[]) {
gridRef.current?.actions.deleteRowsById([...rowIds]);
}A delete clears the selection, so the bar hides itself.
Export only the checked rows
exportGrid takes the grid state and scope: "selection". It needs data-grid-io:
function exportChecked(gridRef: RefObject<DataGridApi<Order> | null>) {
const api = gridRef.current;
if (api) void exportGrid(api.store.getState(), { scope: "selection", format: "csv" });
}Related
- Events & state: Reading the selected rows:
getRowIds()covers marker checks and ranges. - Row operations: the row actions behind
deleteRows. - Server round-trip: send the bulk change to an API.