Birch UI v0.1
Pricing

Custom cell context menu

Add row actions to the grid's right-click menu, keep or drop the built-in copy and export items, and disable the menu entirely with the contextMenu option.

Open .md

Right-clicking a cell opens a menu with Copy cell, Copy row, Copy with headers and Export CSV. This recipe adds order actions to that menu with the contextMenu option.

Custom context menu

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/recipe-grid-context-menu.ts
import { createGrid, type ColumnDef, type GridApi } from '@birchui/core';
import { docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order } from './_shared';

export const meta = { title: 'Custom context menu', height: 440 };

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', flex: 1, minWidth: 170 },
  { field: 'product', header: 'Product', width: 190 },
  { field: 'status', header: 'Status', width: 120 },
  { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append('Right-click a cell, or focus one and press Shift+F10.');
  const setStatus = (api: GridApi<Order>, order: Order, next: Order['status']) => {
    api.setValue(order, 'status', next);
    status.textContent = `${order.id} marked as ${next}.`;
  };
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(150, 3),
    getRowId: (order) => order.id,
    theme: docsTheme(),
    ariaLabel: 'Orders with a context menu',
    contextMenu: (ctx, defaults) => {
      const order = ctx.row;
      if (!order) return defaults;
      return [
        {
          label: 'Mark as shipped',
          disabled: order.status !== 'Pending',
          action: () => setStatus(ctx.api, order, 'Shipped'),
        },
        {
          label: 'Mark as returned',
          disabled: order.status !== 'Delivered',
          action: () => setStatus(ctx.api, order, 'Returned'),
        },
        {
          label: `Filter to ${order.customer}`,
          separatorBefore: true,
          action: () => ctx.api.setQuickFilter(order.customer),
        },
        { label: 'Clear filter', action: () => ctx.api.setQuickFilter('') },
        ...defaults.map((item, index) => (index === 0 ? { ...item, separatorBefore: true } : item)),
      ];
    },
  });
  status.textContent = 'Custom actions appear above the built-in copy and export items.';
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    stopTheme();
    grid.destroy();
  };
}

1. Add your items#

contextMenu is true (the default), false, or a function that receives the cell context and the default items and returns the items to show:

orders-grid.ts
import { createGrid, type MenuItem } from '@birchui/core';
import { openOrderDrawer, shipOrder } from './orders-actions';

const grid = createGrid(document.querySelector<HTMLElement>('#orders')!, {
  columns,
  rows: orders,
  getRowId: (order) => order.id,
  contextMenu: (ctx, defaults) => {
    const order = ctx.row;
    if (!order) return defaults;
    const actions: MenuItem[] = [
      { label: 'Open order', action: () => openOrderDrawer(order.id) },
      {
        label: 'Mark as shipped',
        disabled: order.status !== 'Pending',
        action: async () => {
          await shipOrder(order.id);
          ctx.api.setValue(order, 'status', 'Shipped');
        },
      },
      {
        label: `Show only ${order.customer}`,
        separatorBefore: true,
        action: () => ctx.api.setFilter('customer', { type: 'text', op: 'equals', value: order.customer }),
      },
    ];
    return [...actions, ...defaults.map((item, i) => (i === 0 ? { ...item, separatorBefore: true } : item))];
  },
});

The context gives you the row (ctx.row), the column (ctx.column), the raw and formatted value, the display row and the grid API.

MenuIteminterface@birchui/coreFull reference
PropertyTypeDescription
labelstring—
action() => void—
checkedoptionalboolean—
disabledoptionalboolean—
separatorBeforeoptionalboolean—

2. Per-column menus#

Return different items depending on the column:

TypeScript
contextMenu: (ctx, defaults) => {
  if (ctx.column.id === 'customer' && ctx.row) {
    return [{ label: `Email ${ctx.row.customer}`, action: () => composeEmail(ctx.row!.customerEmail) }, ...defaults];
  }
  return defaults;
},

3. Remove the menu#

TypeScript
createGrid(container, { columns, rows, contextMenu: false });

With false, right-click shows the browser's own menu. Returning an empty array from the function also suppresses the grid menu for that cell, which is how to disable it only on some columns.

How it works#

  • The menu opens on right-click, and from the keyboard with Shift+F10 or the context menu key on a focused cell. Focus returns to the cell when the menu closes.
  • Installed Grid Pro modules contribute their own items, for example the fill handle's Fill down. They are part of defaults, after the built-in items.
  • Opening the menu stops any edit in progress and focuses the clicked cell.
  • Right-clicking inside an editor or another text input shows the browser menu, so spell-check and paste keep working.
  • If your function throws or returns something other than an array, the grid shows the default items and logs the problem.

Pitfalls#

  • Labels are not translated for you. Use your own translations for item labels; the built-in items follow the grid's localeText.
  • Keep actions quick. action runs when the item is chosen; for slow work, update the UI optimistically or show progress elsewhere, since the menu closes immediately.
  • Group and detail rows. ctx.row is undefined on group rows, so check it before reading fields. Full-width rows such as detail panels open no menu.

↑ ↓ to move, Enter to open, Esc to close