gridcn2.0.0
Editing cells

Lock cells by role

Make cells read-only and remove columns based on the role of the signed-in user.

The grid has no role model. Derive the lock from your own session or auth hook. A column's readOnly function locks cells. The columns array decides which columns exist.

Before you start, know the limit of the check. A role rule in the grid changes only what the browser shows and accepts. Enforce the same rule on your server.

Steps

  1. Copy the hook below.
  2. Replace useSession with your auth hook.
  3. Pass useOrderColumns() as columns.

The hook applies three rules:

  • readOnly locks a column for a role. The function receives the row, so a role gate and a per-row gate combine in one expression.
  • A column that the array leaves out does not exist for that role.
  • useMemo on the role gives the grid a new array only after a role change.

This hook applies the three rules:

import { useMemo } from "react";
import {
  defineColumns,
  type ColumnDef,
} from "@/components/data-grid/data-grid";

type Role = "admin" | "member" | "guest";
type Order = {
  id: string;
  customerName: string;
  price: number;
  internalNote: string;
  locked: boolean;
};

// Replace this stub with your own auth hook.
function useSession(): { role: Role } {
  return { role: "member" };
}

export function useOrderColumns(): ColumnDef<Order>[] {
  const { role } = useSession();

  return useMemo(() => {
    const columns = defineColumns<Order>()([
      { id: "customerName", header: "Customer", accessorKey: "customerName" },
      {
        id: "price",
        header: "Price",
        accessorKey: "price",
        type: "number",
        readOnly: (row) => role !== "admin" || row.locked,
      },
      {
        id: "internalNote",
        header: "Internal note",
        accessorKey: "internalNote",
      },
    ]);
    return columns.filter(
      (column) => role !== "guest" || column.id !== "internalNote",
    );
  }, [role]);
}

Result

price combines two conditions: only an admin can edit it, and a locked order accepts no edits from anyone. A locked cell rejects typed edits, paste, fill, and clear. A guest gets no internalNote column. A removed column hides the field in the grid only. The field stays in every row object that the browser holds, so strip it on the server.

Column readOnly does not stop a row delete: Ctrl+Shift+Backspace deletes the active row. For a role that must not change rows, set readOnly on the grid. To keep cell edits, set enableRowDelete={false} or return false from onBeforeDeleteRows. Then pass no createRow, no duplicateRow, and no reorder rowMarkers mode for that role.

When the role changes, the new array replaces the columns, and the new readOnly rule applies from then on.

Hidden columns are not removed columns

hidden: true hides a column, but the user can show it again from the columns menu. Leave the column out of the array to remove it.

On this page