Skip to main content

ContextMenu

Open item-specific actions at a context interaction point.

Props
Slots

Anatomy#

ContextMenu [component; no DOM]
├── ContextMenu.Trigger [part; slot=trigger]
├── overlay [slot]
└── positioner [internal]
    └── ContextMenu.Content [part; slot=content]
        ├── group [slot]
        │   ├── groupLabel [slot]
        │   └── item [slot]
        ├── item [slot]
        │   ├── itemLeading [slot]
        │   ├── itemWrapper [slot]
        │   │   ├── itemLabel [slot]
        │   │   └── itemDescription [slot]
        │   └── itemTrailing [slot]
        │       ├── itemKbds [slot]
        │       ├── itemIndicator [slot]
        │       └── itemSubIndicator [slot]
        └── separator [slot]

Content is portaled; grouped items use the same item subtree as ungrouped items.

Usage#

Use ContextMenu for actions tied to a specific surface or item at the pointer location. Use DropdownMenu when the same actions open from a visible trigger. Use Popover when the content is not a list of commands. Use Dialog when the user must complete or confirm a modal task. Keep essential actions reachable through another visible path.

import { ContextMenu } from 'moraine'

export function Example() {
  return (
    <ContextMenu>
      <ContextMenu.Trigger>Right-click here</ContextMenu.Trigger>
      <ContextMenu.Content items={[{ label: 'Copy' }]} />
    </ContextMenu>
  )
}

Triggering the menu#

Wrap the target with ContextMenu.Trigger. The menu opens at the pointer on right-click, or at the center of the trigger when opened from the keyboard. A touch or pen long press (700 ms) also opens it. The trigger renders a div; pass as to render another element. With disabled on the root, the native browser menu shows instead.

<ContextMenu>
  <ContextMenu.Trigger as="div" class="flex h-32 items-center justify-center">
    Right-click or long-press inside this area
  </ContextMenu.Trigger>
  <ContextMenu.Content
    items={[
      { label: 'Back', icon: 'i-lucide:arrow-left' },
      { label: 'Forward', icon: 'i-lucide:arrow-right', disabled: true },
      { label: 'Reload', icon: 'i-lucide:rotate-cw' },
    ]}
  />
</ContextMenu>

Item models#

The items array describes the whole menu. An item has type 'item' (the default), 'checkbox', 'radio-group', 'group', or 'separator'; an item with children opens a submenu. Items accept icon, description, kbds, disabled, and variant: 'danger'. kbds only displays keycaps and does not register a shortcut. An entry that is an array of items forms its own group, and the menu draws a separator between groups.

Checkbox and radio state is controlled with checked / onCheckedChange and with value / onValueChange on the radio-group (not on each radio). Omit them to let the item manage its own state, starting from defaultChecked or defaultValue. Selecting a checkbox or radio keeps the menu open; selecting a regular item runs onSelect and closes it.

A parent item with children can take open and onOpenChange to control its submenu. onOpenChange reports every open or close request from pointer, keyboard, or click interaction. With a controlled open, the submenu stays at the prop value until you update it.

<ContextMenu.Content
  items={[
    {
      type: 'checkbox',
      label: 'Pin item',
      checked: pinned(),
      onCheckedChange: setPinned,
    },
    { type: 'separator' },
    {
      type: 'radio-group',
      value: priority(),
      onValueChange: setPriority,
      items: [{ type: 'radio', label: 'High priority', value: 'high' }],
    },
  ]}
/>

ContextMenu.Content also takes headerRender and footerRender to add a header (such as the target’s metadata) or a footer around the item groups, in the root menu and in every submenu. Both receive { sub }. itemRender replaces the inner content of every item row; the row keeps its role, keyboard handling, and selection.

Dismissal and scrolling#

Escape and outside presses close the menu. Set closeOnEscape or closeOnOutsideClick to false to block them, and use onClosePrevented to react to the blocked attempt. While the menu is open, body scroll is locked and an overlay renders behind the content; set preventScroll to false to keep the page scrollable. Set modal to hide outside content from assistive technology while the menu is open.

Keyboard interaction#

Key Description
Shift + F10 / ContextMenu Toggles the menu from the focused trigger.
↓ / ↑ Moves focus to the next or previous item.
↖ / ↘ Moves focus to the first or last item.
Printable characters Moves focus to the next item whose text starts with the typed characters.
→ Opens the submenu of the focused item.
← Closes the current submenu and returns to its parent item.
↵ / Space Activates the focused item, or opens its submenu.
Esc Closes the current menu layer and restores focus.
⇥ Closes the menu.

Examples#

Open page actions on a selected surface#

Right-click or long-press the dashed region. Forward stays disabled in this example.

import { ContextMenu } from 'moraine'
import type { ContextMenuT } from 'moraine'

const MENU_ITEMS = [
  { label: 'Back', icon: 'i-lucide:arrow-left' },
  { label: 'Forward', icon: 'i-lucide:arrow-right', disabled: true },
  { label: 'Reload', icon: 'i-lucide:rotate-cw' },
] satisfies ContextMenuT.Item[]

export function TriggerUsage() {
  return (
    <div class="max-w-md w-full">
      <ContextMenu>
        <ContextMenu.Trigger
          as="div"
          class="text-xs text-muted-foreground b-2 b-border rounded-xl b-dashed flex h-32 w-full select-none items-center justify-center"
        >
          Right-click or long-press inside this area
        </ContextMenu.Trigger>
        <ContextMenu.Content items={MENU_ITEMS} />
      </ContextMenu>
    </div>
  )
}

Copy, rename, or delete a file#

Describe grouped actions in the item model, including a danger-variant delete.

import { ContextMenu } from 'moraine'

export function ItemsUsage() {
  return (
    <div class="max-w-md w-full">
      <ContextMenu>
        <ContextMenu.Trigger
          as="div"
          class="text-xs text-muted-foreground b-1 b-border rounded-xl flex h-28 w-full select-none items-center justify-center"
        >
          Right-click to view item model actions
        </ContextMenu.Trigger>
        <ContextMenu.Content
          items={[
            {
              label: 'Actions',
              children: [
                { label: 'Copy path', icon: 'i-lucide:copy' },
                { label: 'Rename file', icon: 'i-lucide:edit-2' },
                { label: 'Delete', icon: 'i-lucide:trash-2', variant: 'danger' },
              ],
            },
          ]}
        />
      </ContextMenu>
    </div>
  )
}

Manage a project file#

Move a file between folders, add it to favorites, or move it to the trash and undo. These actions update local example state; permission-dependent actions remain disabled.

import { Button, ContextMenu, Icon } from 'moraine'
import type { ContextMenuT } from 'moraine'
import { createMemo, createSignal, Show } from 'solid-js'

export function FileActions() {
  const [folder, setFolder] = createSignal('Projects')
  const [favorite, setFavorite] = createSignal(false)
  const [deleted, setDeleted] = createSignal(false)
  const [status, setStatus] = createSignal('Right click the file, long press, or use Shift + F10.')
  const items = createMemo<ContextMenuT.Item[]>(() => [
    {
      type: 'group',
      label: 'Project brief.pdf',
      children: [
        {
          label: 'Open preview',
          icon: 'i-lucide:eye',
          onSelect: () => setStatus('Preview ready: Project brief.pdf · 4 pages · 240 KB'),
        },
        {
          type: 'checkbox',
          label: 'Add to favorites',
          checked: favorite(),
          onCheckedChange: (checked: boolean) => {
            setFavorite(checked)
            setStatus(checked ? 'Added to favorites.' : 'Removed from favorites.')
          },
        },
      ],
    },
    { type: 'separator' },
    {
      label: 'Move to',
      icon: 'i-lucide:folder-input',
      children: ['Projects', 'Shared', 'Archive'].map((destination) => ({
        label: destination,
        icon: 'i-lucide:folder',
        disabled: folder() === destination,
        onSelect: () => {
          setFolder(destination)
          setStatus(`Moved to ${destination}.`)
        },
      })),
    },
    {
      label: 'Manage access',
      description: 'Only the owner can change permissions',
      icon: 'i-lucide:lock',
      disabled: true,
    },
    { type: 'separator' },
    {
      label: 'Move to trash',
      icon: 'i-lucide:trash-2',
      variant: 'danger',
      onSelect: () => {
        setDeleted(true)
        setStatus('Project brief.pdf moved to trash.')
      },
    },
  ])

  return (
    <section class="max-w-lg w-full space-y-3" aria-label="File actions example">
      <Show
        when={!deleted()}
        fallback={
          <div class="p-4 border border-border rounded-lg border-dashed flex gap-3 items-center justify-between">
            <span class="text-sm text-muted-foreground">File is in the trash</span>
            <Button
              variant="outline"
              onClick={() => {
                setDeleted(false)
                setStatus('Project brief.pdf restored.')
              }}
            >
              Undo
            </Button>
          </div>
        }
      >
        <ContextMenu>
          <ContextMenu.Trigger
            class="p-4 outline-none border border-border rounded-lg bg-card flex gap-3 select-none items-center focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
            aria-label="Actions for Project brief.pdf"
          >
            <Icon name="i-lucide:file-text" class="text-muted-foreground shrink-0 size-8" />
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium truncate">Project brief.pdf</p>
              <p class="text-xs text-muted-foreground">{folder()} · 240 KB</p>
            </div>
            <Show when={favorite()}>
              <Icon name="i-lucide:star" class="text-primary size-4" />
            </Show>
          </ContextMenu.Trigger>
          <ContextMenu.Content items={items()} />
        </ContextMenu>
      </Show>
      <p role="status" class="text-xs text-muted-foreground">
        {status()}
      </p>
    </section>
  )
}

Pin an item and set priority#

Checkbox and radio values live in application state. The status line reflects the current pin and priority.

import { ContextMenu } from 'moraine'
import type { ContextMenuT } from 'moraine'
import { createMemo, createSignal } from 'solid-js'

export function CheckboxRadio() {
  const [pinned, setPinned] = createSignal(false)
  const [priority, setPriority] = createSignal('normal')
  const items = createMemo<ContextMenuT.Item[]>(() => [
    { type: 'checkbox', label: 'Pin item', checked: pinned(), onCheckedChange: setPinned },
    { type: 'separator' },
    {
      type: 'radio-group',
      value: priority(),
      onValueChange: setPriority,
      items: [
        { type: 'radio', label: 'Low priority', value: 'low' },
        { type: 'radio', label: 'Normal priority', value: 'normal' },
        { type: 'radio', label: 'High priority', value: 'high' },
      ],
    },
  ])

  return (
    <div class="space-y-3">
      <ContextMenu>
        <ContextMenu.Trigger
          as="div"
          class="text-sm text-muted-foreground border border-border rounded-lg border-dashed flex h-28 max-w-sm select-none items-center justify-center"
        >
          Right click to change options
        </ContextMenu.Trigger>
        <ContextMenu.Content items={items()} />
      </ContextMenu>
      <p class="text-sm text-muted-foreground">
        Pinned: {String(pinned())}; priority: {priority()}
      </p>
    </div>
  )
}

Sort from a nested menu#

Nested children open a sort submenu. Refresh stays on the root menu.

import { ContextMenu } from 'moraine'

export function Submenus() {
  return (
    <ContextMenu>
      <ContextMenu.Trigger
        as="div"
        class="text-sm text-muted-foreground border border-border rounded-lg border-dashed flex h-28 max-w-sm select-none items-center justify-center"
      >
        Right click for a submenu
      </ContextMenu.Trigger>
      <ContextMenu.Content
        items={[
          {
            label: 'Sort by',
            children: [
              {
                type: 'group',
                items: [
                  { label: 'Name', icon: 'i-lucide:arrow-down-a-z' },
                  { label: 'Modified date', icon: 'i-lucide:calendar-arrow-down' },
                ],
              },
            ],
          },
          { label: 'Refresh', icon: 'i-lucide:refresh-cw' },
        ]}
      />
    </ContextMenu>
  )
}

Copy a note on long press#

Touch and hold for about 700 ms, or right-click, to copy or delete the note.

import { ContextMenu } from 'moraine'

export function LongPress() {
  return (
    <ContextMenu>
      <ContextMenu.Trigger
        as="div"
        class="text-sm text-muted-foreground text-center border border-border rounded-lg border-dashed flex h-32 max-w-sm select-none items-center justify-center touch-none"
      >
        Touch and hold for about 700 ms, or right click
      </ContextMenu.Trigger>
      <ContextMenu.Content
        items={[
          { label: 'Copy note', icon: 'i-lucide:copy' },
          { label: 'Delete note', variant: 'danger', icon: 'i-lucide:trash-2' },
        ]}
      />
    </ContextMenu>
  )
}

API Reference#

Attributes#

Attributes
data-closed
Slot: context-menu-triggercontext-menu-content
Description: Present when disclosure or transition content is closed.
data-disabled
Slot: context-menu-triggercontext-menu-item
Description: Present when the component, slot, or item is disabled.
data-expanded
Slot: context-menu-triggercontext-menu-contentcontext-menu-item
Description: Present when the panel, accordion, or menu is expanded.
data-align
Slot: context-menu-content
Description: Stores the resolved alignment of positioned content.
data-side
Slot: context-menu-content
Description: Stores the resolved floating or drawer content side.
data-danger
Slot: context-menu-item
Description: Present when the action has danger semantics.
data-highlighted
Slot: context-menu-item
Description: Present when the item is highlighted by pointer or keyboard navigation.
data-selected
Slot: context-menu-item
Description: Present when the item or tab is selected.

Props#

ContextMenu#

Prop

Trigger#

Renders a <div> element by default.

Prop

Content#

Props for the ContextMenu content component. Renders a <div> element by default.

Prop