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]
└── positioner [internal]
    └── ContextMenu.Content [part; slot=content]
        ├── group [slot]
        │   ├── groupLabel [slot]
        │   └── item [slot]
        ├── item [slot]
        │   ├── itemLeading [slot]
        │   ├── itemLabel [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. Keep essential actions reachable through another visible path.

  • 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.
import { ContextMenu } from 'moraine'

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

Trigger#

Wrap the target with ContextMenu.Trigger. The menu opens at the pointer on right-click or a touch or pen long press (700 ms), and at the center of the trigger when opened from the keyboard.

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>

Items#

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. An entry that is an array of items forms its own group, and the menu draws a separator between groups.

Items accept icon, kbds, disabled, and danger; a separator takes no other options. kbds only displays keycaps and does not register a shortcut.

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 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,
      children: [{ type: 'radio', label: 'High priority', value: 'high' }],
    },
  ]}
/>

ContextMenu.Content also takes headerRender and footerRender components to add a header (such as the target’s metadata) or a footer around the item groups. The root menu and every open submenu mount their own copy, and each receives { 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 by default; set preventScroll to false to keep the page scrollable.

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#

Basic#

Right-click or long-press the trigger area to open the menu. Individual items can be marked disabled.

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>
  )
}

Grouped items#

Pass arrays of items to form groups; the menu draws a separator between them. danger: true marks the destructive action.

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 grouped file actions
        </ContextMenu.Trigger>
        <ContextMenu.Content
          items={[
            [
              { label: 'Copy path', icon: 'i-lucide:copy' },
              { label: 'Rename file', icon: 'i-lucide:edit-2' },
            ],
            [{ label: 'Delete', icon: 'i-lucide:trash-2', danger: true }],
          ]}
        />
      </ContextMenu>
    </div>
  )
}

Stateful actions#

Combine submenus, stateful toggles, disabled items, and dynamic actions in one item model.

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.')
          },
        },
      ],
    },
    {
      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',
      icon: 'i-lucide:lock',
      disabled: true,
    },
    { type: 'separator' },
    {
      label: 'Move to trash',
      icon: 'i-lucide:trash-2',
      danger: true,
      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>
  )
}

Checkbox and radio#

Bind checkbox and radio menu items to application state.

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,
      children: [
        { 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>
  )
}

Pass nested children on an item to open a submenu.

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',
                children: [
                  { 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>
  )
}

Long press#

Touch and hold for ~700 ms on touch devices, or right-click with a pointer, to open the menu.

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', danger: true, 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