gridcn2.0.0
Row examples

Context menu items example

Keep only some built-in items in the cell menu and the header menu with the item resolvers of DataGridContextMenu.

DataGridContextMenu builds each menu from a resolver. The resolver receives the built-in items as defaults and returns the list that the menu shows. In the demo, the cell menu keeps two row items, and the header menus keep one sort item.

The menus are data: each resolver receives the built-in item set and returns the kept entries by id. Right-click a cell for the two kept row items; the header dropdown and the right-click header menu both keep only Sort ascending.

Name
Email
Score
Silent Tiger
user0@example.com
4
Quick Lion
user1@example.com
89
Swift Wolf
user2@example.com
80
Eager Lion
user3@example.com
51
Eager Tiger
user4@example.com
83
Silent Wolf
user5@example.com
15
Swift Lion
user6@example.com
62
Eager Lion
user7@example.com
42
Eager Eagle
user8@example.com
35
Bold Tiger
user9@example.com
52
pnpm dlx shadcn@latest add @gridcn/data-grid-context-menu-slots-demo

What the demo shows

  • A right-click on a cell shows Insert row below and Duplicate row (Duplicate rows when the selection covers more rows). getCellMenuItems keeps the items with the ids insert-row-below and duplicate-rows.
  • The createRow and duplicateRow props turn on the two kept items. Without them, the menu hides those items.
  • The header dropdown and a right-click on a header both show Sort ascending only. getHeaderMenuItems keeps the sort-asc item. The header resolver applies to both header surfaces.

The resolvers filter defaults by id:

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import {
  DataGridContextMenu,
  DataGridHeaderDropdown,
} from "@/components/data-grid-context-menu/data-grid-context-menu";

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

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

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

const keptCellItems = new Set(["insert-row-below", "duplicate-rows"]);

export function TrimmedMenuGrid() {
  return (
    <DataGridProvider
      defaultData={rows}
      columns={columns}
      createRow={() => ({ id: crypto.randomUUID(), name: "" })}
      duplicateRow={(row) => ({ ...row, id: crypto.randomUUID() })}
    >
      <DataGridContextMenu
        getCellMenuItems={(_ctx, defaults) =>
          defaults.filter((item) => keptCellItems.has(item.id))
        }
        getHeaderMenuItems={(_ctx, defaults) =>
          defaults.filter((item) => item.id === "sort-asc")
        }
      >
        <DataGridRoot
          renderHeaderMenu={(ctx) => <DataGridHeaderDropdown {...ctx} />}
        >
          <DataGridHeader />
          <DataGridBody />
        </DataGridRoot>
      </DataGridContextMenu>
    </DataGridProvider>
  );
}

On this page