gridcn2.0.0
Learning path

Edit cells

Step 4 of 8

Lock cells and reject bad values before they enter the data, building on the columns of the first grid.

Before you start, define the columns.

This step locks the Name cells of inactive people and rejects an Age under 18. The keys that start, commit, and cancel an edit are in Render your first grid.

Lock and validate

A column with accessorKey is editable until you lock it. readOnly takes true or a function of the row. validate takes a function that returns an error message, or null to accept the value.

Replace columns.ts with this file:

columns.ts
import { defineColumns } from "@/components/data-grid/data-grid";

export type Person = { id: string; name: string; age: number; active: boolean };

export const columns = defineColumns<Person>()([
  {
    id: "name",
    header: "Name",
    accessorKey: "name",
    type: "text",
    width: 200,
    pin: "start",
    readOnly: (person) => !person.active,
  },
  {
    id: "age",
    header: "Age",
    accessorKey: "age",
    type: "number",
    width: 90,
    options: { min: 0, max: 120 },
    validate: (value) =>
      typeof value === "number" && value < 18 ? "Must be 18 or older" : null,
  },
  {
    id: "active",
    header: "Active",
    accessorKey: "active",
    type: "checkbox",
    width: 90,
  },
  {
    id: "group",
    header: "Group",
    accessorFn: (person) => (person.age >= 18 ? "Adult" : "Minor"),
    flex: 1,
  },
]);

Result: clear the Active checkbox of a row, and its Name cell rejects typing, pastes, and Delete. Type 12 in an Age cell and press Enter. The editor stays open and shows the message. The value never enters the data. Press Escape to cancel.

Other ways to lock and validate

  • readOnly on <DataGrid> locks every user write in every column: editing, paste, fill, cut, delete, row operations, undo, and redo.
  • validationMode: "warn" on a column commits a rejected edit, paste, or fill and flags the cell. The default, "block", refuses the commit.
  • validate also takes a Standard Schema, such as a Zod schema, in place of the function.
  • The cell type picks the editor: a text input, a number input, a date picker, or a list of choices.

Next: Keep edits in state.

On this page