FreeGridv1.15.1한국어

Building your own context menu

Build the right-click menu from built-in entries by name and your own entries: submenus, icons, check marks, headings, hidden and danger entries, and a separate menu for headers.

Live demoYour own context menu

Keys, submenus, icons and a header menu.

Code for this demo
import { createGrid, type ColumnDef, type Row } from '@freegridjs/core';
import { makeRows } from '../data';
import { button, separator, text, tr, type DemoContext } from '../ui';

export default function mount(ctx: DemoContext) {
  const h = (en: string, ko: string) => tr(ctx.lang, { en, ko });
  const starred = new Set<unknown>();
  const grid = createGrid(ctx.host, {
    columns: [{ field: 'id', header: 'ID', type: 'number', width: 70 }, { field: 'name', header: h('Name', '이름'), width: 170 }, { field: 'country', header: h('Country', '국가'), width: 140 }, { field: 'q1', header: h('Q1', '1분기'), type: 'number', format: '#,##0', width: 120 }],
    data: makeRows(300), locale: ctx.lang, rowSelection: 'multiple', getRowId: r => String(r.id), cellNotes: true,
    contextMenu: p => [
      { heading: p.row ? h(`Customer #${p.row.id}`, `고객 #${p.row.id}`) : h('Customers', '고객') },
      'copy', 'copyWithHeaders', 'paste', 'undo',
      'separator',
      { label: h('Starred', '즐겨찾기'), icon: '★', checked: starred.has(p.row?.id), disabled: !p.row, action: () => { starred.has(p.row!.id) ? starred.delete(p.row!.id) : starred.add(p.row!.id); ctx.log(`starred: ${[...starred].join(', ')}`); } },
      { label: h('Export', '내보내기'), icon: '⇩', items: ['exportCsv', 'exportExcel', { label: h('More', '기타'), items: ['exportJson', 'exportPdf', 'print'] }] },
      { label: h('Column', '컬럼'), items: ['autosize', 'hideColumn', 'separator', 'pinLeft', 'pinRight', 'unpin'] },
      'note',
      'separator',
      { label: h('Delete row', '행 삭제'), icon: '🗑', danger: true, hidden: !p.row, action: () => grid.removeRows([p.row!]) },
    ],
    headerContextMenu: p => [{ heading: p.column?.header ?? p.colId }, ...p.defaultItems],
  });
  text(ctx, h('Right-click a cell (hover Export for a submenu) or a header. Shift+F10 opens it from the keyboard: ↓ ↑, → opens, ← goes back.',
    '셀(내보내기에 마우스를 올리면 하위 메뉴)이나 헤더를 우클릭하세요. Shift+F10으로 키보드로 열고 ↓ ↑, →로 열고 ←로 돌아갑니다.'));
  return grid;
}

contextMenu (cells) and headerContextMenu (column headers) take a list of entries, or a function that returns one for the cell that was right-clicked. A list mixes built-in entries by name with your own.

A full example

createGrid(el, {
  columns, data, cellNotes: true,
  contextMenu: p => [
    { heading: p.row ? `Order #${p.row.id}` : 'Order' },
    'copy', 'paste',
    'separator',
    { label: 'Starred', icon: '★', checked: !!p.row?.starred, action: () => toggleStar(p.row) },
    { label: 'Export', icon: '<svg viewBox="0 0 16 16"><path d="M8 1v9m-4-4 4 4 4-4M2 14h12" stroke="currentColor" fill="none"/></svg>',
      items: ['exportCsv', 'exportExcel', { label: 'More', items: ['exportJson', 'exportPdf', 'print'] }] },
    { label: 'Refund…', hidden: !p.row?.paid, action: () => refund(p.row) },
    'note',
    'separator',
    { label: 'Delete', icon: '🗑', danger: true, shortcut: 'Del', action: () => grid.removeRows([p.row]) },
  ],
  headerContextMenu: p => [{ heading: p.column?.header ?? p.colId }, ...p.defaultItems],
});

Entries

NameTypeDescription
'separator'stringA line. Lines at the start, the end or next to each other are dropped.
'copy', 'exportExcel' …ContextMenuKeyA built-in entry by name (table below). Entries that do not apply right now are left out.
{ heading }objectA small title over the entries that follow.
{ label, action }objectYour entry; action gets the menu params.
itemsContextMenuItem[]A submenu (opens on hover, click, → or Enter; ← and Esc go back). A submenu with nothing left in it is dropped.
iconstring | HTMLElementText or an emoji, an element, or an SVG string ('<svg…'). Escape untrusted data.
checkedbooleanA check mark in the icon place; screen readers hear a checkbox.
disabled / hiddenbooleanGreyed out / left out.
dangerbooleanRed text for entries that remove things.
shortcut / titlestringA key hint on the right / hover text.

Built-in entries by name

KeyEntryDefault menu
copyCopycells
copyWithHeadersCopy with headerscells
cutCutcells
copyRowsCopy checked rows (when rows are checked)cells
pastePastecells
undo / redoUndo / redo (when there is history)cells
deleteRowsDelete checked rows (danger style)cells
autosize / autosizeAllSize this column / all columns to fitboth
hideColumnHide the column (not for lockVisible)both
pinLeft / pinRight / unpinPin the columnboth
sortAsc / sortDesc / clearSortSort by the column (the current direction checked)headers
groupBy / ungroupGroup by the column / stopheaders
selectAllSelect all rows (rowSelection multiple)cells
chooseColumns / resetColumnsColumn chooser (both) / reset columns (headers)both
chartBar / chartLine / chartPieChart of the selected range (a range of more than one cell)cells
exportCsv / exportExcel / exportJson / exportPdfExport the rowscells
advancedFilterOpen the advanced filtercells
printPrintcells
conditionalFormatConditional formats of the columnheaders
columnMenuOpen the column menu (filters)headers
note / deleteNoteAdd or edit / delete the note of the cell (cellNotes)cells
addCalculated / editCalculated / removeCalculatedCalculated columnsheaders
showValuesAsA submenu: values, % of total, % of group, running totalheaders
expandDetails / collapseDetailsOpen / close every detail row (detailRenderer)cells

Any key works in either menu: sortAsc in the cell menu sorts by the right-clicked column.

What the function and actions get

NameTypeDescription
area'cell' | 'header'Which menu.
row / rowIndexRow | null / numberThe right-clicked row (null and -1 for a header or an empty area).
colId / columnstring / ColumnDef | nullThe column.
valueunknownThe cell value.
defaultItemsContextMenuItem[]The built-in menu, entries with their key: keep, filter, reorder or extend.
  • Without headerContextMenu, a header right-click opens the column menu (as before). false keeps the browser menu.
  • true shows the built-in header menu: sort (current direction checked), pin, group, size, hide, choose and reset columns, show values as, calculated columns, conditional formats and the column menu.
  • A list or a function builds it like the cell menu.

Keyboard

KeyDoes
Shift + F10, ContextMenuOpen the cell menu at the focused cell
↓ / ↑Move between entries
→ / EnterOpen a submenu
← / EscBack to the parent menu; Esc on the first menu closes it

Questions about this page

How do I add a submenu to the grid context menu?

Give an entry items: { label: 'Export', items: ['exportCsv', 'exportExcel'] }. It opens on hover, click, → or Enter, and submenus can nest.