gridcn2.0.0
Rows, pages, and menus

Row operations

Insert, duplicate, and delete rows from props, shortcuts, the context menu, or code, and ask for confirmation before a delete.

Users add, copy, and remove rows while they work. The grid inserts, duplicates, and deletes rows through two factory props, keyboard shortcuts, the context menu, and useDataGridActions. Each operation writes one change with source: "row-operation", or source: "stream" for a stream delete.

Select rows (or just click a cell) and use the toolbar, or right-click a row for the context menu. The panel shows the last onDataChange payload.

Read-only
Name
Role
Age
Silent Tiger
Viewer
63
Quick Lion
Viewer
67
Swift Wolf
Manager
40
Eager Lion
User
50
Eager Tiger
Viewer
45
Silent Wolf
User
24
Swift Lion
Viewer
34
Eager Lion
Manager
21

Enable the operations

Insert needs createRow and duplicate needs duplicateRow. Delete needs no prop. This grid enables all three operations:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Row = { id: string; name: string };

const columns = defineColumns<Row>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

const rows: Row[] = [{ id: "1", name: "Ada" }];

function MyGrid() {
  return (
    <DataGrid
      defaultData={rows}
      columns={columns}
      createRow={() => ({ id: crypto.randomUUID(), name: "" })}
      duplicateRow={(row) => ({ ...row, id: crypto.randomUUID() })}
    />
  );
}
PropTypeDefault
createRow(index: number, ctx: { signal: AbortSignal }) => TData | Promise<TData>none
duplicateRow(row: TData, index: number, ctx: { signal: AbortSignal }) => TData | Promise<TData>none
enableRowDeletebooleantrue
onBeforeDeleteRows(ctx: { rowIds: readonly string[]; hiddenCount: number; signal: AbortSignal }) => boolean | Promise<boolean>none

Without a factory, the operation does nothing, the context menu hides its item, and a programmatic call warns in development. useDataGridRowOps() from data-grid-context-menu returns canCreateRow and canDuplicateRow.

createRow receives the data index of the new row. duplicateRow receives the source row and the data index of the copy. Give the copy a new id.

Both factories can return a promise. The grid waits until every row settles and then writes one change. A newer insert or duplicate aborts the pending one and runs instead. A rejection cancels the operation. The grid drops a late result when it became readOnly or the anchor or source row is gone. ctx.signal aborts in those cases, when gateTimeoutMs runs out, and when the grid unmounts.

If a cell editor is open during an operation, the editor follows its row. An operation that removes the edited row cancels the edit and calls onEditEnd with result: "cancel".

Run from code

useDataGridActions returns the same operations that the shortcuts and the menu run. Call it below DataGridProvider:

import { useDataGridActions } from "@/components/data-grid/data-grid";

function AddRowButton() {
  const actions = useDataGridActions();
  return (
    <button type="button" onClick={() => actions.insertRow(2, "below")}>
      Add row
    </button>
  );
}

insertRow and insertRows address view indexes, the positions the user sees. duplicateRows and deleteRows take row ids, and their At forms take view indexes.

  • insertRow(viewRowIndex, position) inserts one row that createRow builds. position is "above" or "below".
  • insertRows(viewRowIndex, count, position) inserts count rows as one change. createRow runs once per row. A count of 0 or less does nothing.
  • duplicateRows(rowIds) puts each copy directly after its own source row. duplicateRowsAt(viewIndexes) takes view row numbers.
  • deleteRowsAt(viewIndexes) deletes the rows at these view row numbers as one change.
  • deleteRows(rowIds, options?) deletes the rows with these ids as one change. The grid skips an id that matches no row. { source: "stream" } deletes rows that the server removed. See Push into a server-ordered view.

api.runShortcut(action) from useDataGridApi runs what the key of a keymap action runs, on the same rows as the key.

What the operations do to the view:

  • Insert and duplicate shift the selection around the new rows.
  • Under a client sort, a new row lands in its sorted position. Under sortMode="server", it lands next to the row you inserted it beside.
  • Under a sort, a filter, or paging, the range collapses onto the active cell.
  • Delete clears the selection, the active cell, and "all matching". Remembered checks of hidden rows stay, unless "all matching" was on.

Shortcuts

ActionDefaultKeymap action
Insert row aboveCtrl/Cmd+Shift+UinsertRowAbove
Insert row belowCtrl/Cmd+Shift+FinsertRowBelow
Duplicate rowsCtrl/Cmd+Shift+XduplicateRow
Delete rowsCtrl/Cmd+Shift+BackspacedeleteRows

Insert works at the active cell. Duplicate and delete work on every row that the selection covers. With no selection, they work on the active row. With 'until-cleared' or 'across-filters' and at least one checked row, they work on the checked rows only. A readOnly grid ignores all four keys, and enableRowDelete={false} turns off the delete key and the Delete rows menu item. onRowActionSkipped tells why a key did nothing. The Delete key clears cell contents and never deletes rows.

Remap or remove these DEFAULT_KEYMAP keys through the keymap prop, as Shortcut remapping shows.

Confirm a delete

onBeforeDeleteRows runs before every delete the grid starts: the shortcut, the context menu item, deleteRows without source: "stream", and deleteRowsAt. It receives rowIds, the ids that go, and hiddenCount, the number of hidden checked rows that stay. It also receives signal. The signal aborts when the grid becomes readOnly, the rows or the checked rows change, gateTimeoutMs runs out, or the grid unmounts. Return false or a promise of false to cancel. Without the prop, a delete runs at once.

A bulk delete button calls deleteRows, so this check runs too. Run bulk actions builds the bar.

This sample resolves a promise from the buttons of a dialog:

import { useState } from "react";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

type Row = { id: string; name: string };
type Ask = { count: number; answer: (ok: boolean) => void };

const columns = defineColumns<Row>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

const rows: Row[] = [{ id: "1", name: "Ada" }];

function GridWithConfirm() {
  const [ask, setAsk] = useState<Ask | null>(null);

  const confirmDelete = ({ rowIds }: { rowIds: readonly string[] }) =>
    new Promise<boolean>((resolve) => {
      setAsk({ count: rowIds.length, answer: resolve });
    });

  const settle = (ok: boolean) => {
    ask?.answer(ok);
    setAsk(null);
  };

  return (
    <>
      <DataGrid
        defaultData={rows}
        columns={columns}
        onBeforeDeleteRows={confirmDelete}
      />
      <Dialog
        open={ask !== null}
        onOpenChange={(open) => !open && settle(false)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete {ask?.count} rows?</DialogTitle>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => settle(false)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={() => settle(true)}>
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

A newer delete aborts the pending one and runs instead. After the promise resolves, the grid reads its state again. If the grid became readOnly, it drops a true result. It also drops the result after a change of the row set or the checks. A callback that throws or rejects cancels the delete and warns in development.

Settle the promise on every path, also when the user dismisses the dialog. A promise that never settles waits until a newer delete replaces it. gateTimeoutMs aborts it. Without that prop, the grid warns once in development after 30 seconds.

Clearing cell contents with Delete skips onBeforeDeleteRows. With the history add-on, undo restores a confirmed delete.

Server mode

Row operations change the rows in memory and never ask a server for rows. Each operation calls onDataChange and then onSave with the same change. change.ops holds one insert or delete operation per row, keyed by row id. A moved row has a move operation.

If the promise from onSave rejects, or resolves with a rejected entry for a row, the grid reverts that row. A refused insert removes the row. A refused delete restores it. Handle refused saves shows the full contract.

Two data modes change the scope of an operation:

  • Client pagination. data stays the whole array, and view indexes address the shown page. onDataChange receives the whole array. Store it as it is. See Client pagination.
  • Scroll mode. Unloaded rows are holes. If the target of a delete, duplicate, or insert touches a hole, the operation does nothing and returns { ok: false, reason: "unloaded-rows" }. One hole cancels the whole request, so leave placeholder ids out. The grid calls no onDataChange and warns once in development. To delete rows that you know, pass their ids to deleteRows.

On this page