oakoss/ui
Components

Context Menu

A menu of actions opened at the pointer by right-click, long press or the keyboard.

SourceReact Aria
report.pdf

Installation

npx shadcn@latest add @oakoss/context-menu

This also installs Popover, whose panel the menu opens in.

Usage

import {
  ContextMenu,
  ContextMenuItem,
  ContextMenuTrigger,
} from '#/components/ui/overlays/context-menu';
import { Pressable } from 'react-aria-components';

<ContextMenuTrigger>
  <Pressable>
    <div aria-label="report.pdf" role="button" tabIndex={0}>
      report.pdf
    </div>
  </Pressable>
  <ContextMenu onAction={(key) => run(key)}>
    <ContextMenuItem id="open">Open</ContextMenuItem>
    <ContextMenuItem id="delete" intent="destructive">
      Delete
    </ContextMenuItem>
  </ContextMenu>
</ContextMenuTrigger>;

The target is a React Aria component, or a focusable element inside React Aria's Pressable, so the keyboard can reach it. Its items, groups, labels, separators and submenus are Dropdown Menu's with context-menu-* slots, so they take the same props.

Examples

With a visible menu

A context menu is a shortcut, not the only way to an action, so the same actions also sit in a Dropdown Menu on the item.

report.pdf

Accessibility

React Aria opens the menu on the browser's contextmenu event, which a right-click, Ctrl + click on macOS and a long press on Android fire. On iOS, which doesn't fire it, a long press opens the menu. The menu opens with its corner on the pointer, and from the keyboard where the browser places the event; on macOS, in browsers that fire no event for Ctrl + Enter, it opens at the middle of the target. It's named by its target.

The target announces no popup, since opening a menu isn't its main action. The menu keeps focus while open and returns it to the target on close; inside it, the keys are Dropdown Menu's, and the menu itself has focus first, so ↓ moves to the first item.

KeyAction
Shift + F10, the context menu keyOpens the menu on Windows and Linux
Ctrl + EnterOpens the menu on macOS
EscapeCloses the menu

API

ContextMenuTrigger

Renders React Aria's MenuTrigger with trigger="contextMenu". Accepts its props except trigger.

ContextMenu

The popover and its menu, as DropdownMenu, with an offset of 0 so it sits on the pointer.

Props

Prop

Type

Also accepts all React Aria Menu props.

Data attributes

AttributePresent when
data-slotAlways: context-menu-content (the panel), context-menu-list
data-enteringThe panel is fading in
data-exitingThe panel is fading out

Other parts

ContextMenuItem, ContextMenuGroup, ContextMenuLabel, ContextMenuSeparator, ContextMenuSub, ContextMenuSubTrigger and ContextMenuSubContent take Dropdown Menu's props, with context-menu-* in place of dropdown-menu-* in their data-slots.