Skip to content

Context Menu

Opens a list of actions at the pointer when the user right clicks, long presses or uses the context menu key on an element.

Installation

pnpm dlx shadcn@latest add @silkware/context-menu

To copy the component by hand, install its dependencies:

pnpm add react-aria-components class-variance-authority cn lucide-react

Then copy the source into components/ui/context-menu.tsx:

components/ui/context-menu.tsx
"use client"
import * as React from "react"import { cva } from "class-variance-authority"import { cn } from "cn"import {  composeRenderProps,  Header as HeaderPrimitive,  MenuItem as MenuItemPrimitive,  Menu as MenuPrimitive,  MenuSection as MenuSectionPrimitive,  MenuTrigger as MenuTriggerPrimitive,  Popover as PopoverPrimitive,  Separator as SeparatorPrimitive,  SubmenuTrigger as SubmenuTriggerPrimitive,  type MenuItemProps as MenuItemPrimitiveProps,  type MenuSectionProps as MenuSectionPrimitiveProps,} from "@animate-ui/react/primitives/react-aria"import { CheckIcon, ChevronRightIcon } from "lucide-react"
function ContextMenu({  "data-slot": dataSlot = "context-menu-content",  placement = "bottom start",  offset = 4,  crossOffset = 0,  className,  children,  ...props}: Omit<  React.ComponentProps<typeof MenuPrimitive<object>>,  "children" | "className"> &  Pick<    React.ComponentProps<typeof PopoverPrimitive>,    "placement" | "offset" | "crossOffset"  > & {    "data-slot"?: string    className?: string    children?: React.ReactNode  }) {  return (    <PopoverPrimitive      data-slot={dataSlot}      placement={placement}      offset={offset}      crossOffset={crossOffset}      className={cn("z-50 w-(--trigger-width) min-w-36 origin-(--trigger-anchor-point) overflow-x-hidden overflow-y-auto rounded-md bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none data-exiting:overflow-hidden **:data-[slot$=-item]:data-focused:bg-foreground/10", className )}    >      <MenuPrimitive        className="max-h-[inherit] overflow-x-hidden overflow-y-auto outline-hidden"        {...props}      >        {children}      </MenuPrimitive>    </PopoverPrimitive>  )}
function ContextMenuTrigger({  ...props}: Omit<React.ComponentProps<typeof MenuTriggerPrimitive>, "trigger">) {  return (    <MenuTriggerPrimitive      data-slot="context-menu"      trigger="contextMenu"      {...props}    />  )}
function ContextMenuGroup({  ...props}: Omit<MenuSectionPrimitiveProps<object>, "children"> & {  children?: React.ReactNode}) {  return <MenuSectionPrimitive data-slot="context-menu-group" {...props} />}
function ContextMenuLabel({  className,  inset,  ...props}: React.ComponentProps<typeof HeaderPrimitive> & {  inset?: boolean}) {  return (    <HeaderPrimitive      data-slot="context-menu-label"      data-inset={inset}      className={cn(        "px-2 py-1.5 text-xs font-medium text-muted-foreground data-inset:pl-8",        className      )}      {...props}    />  )}
const contextMenuItemVariants = cva(  "group/context-menu-item relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",  {    variants: {      selectionMode: {        none: "gap-2 rounded-sm px-2 py-1.5 text-sm focus:bg-accent focus:text-accent-foreground data-inset:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",        single:          "gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm focus:bg-accent focus:text-accent-foreground data-inset:pl-8 [&_svg:not([class*='size-'])]:size-4",        multiple:          "gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm focus:bg-accent focus:text-accent-foreground data-inset:pl-8 [&_svg:not([class*='size-'])]:size-4",      },    },  })
function ContextMenuItem({  className,  inset,  variant = "default",  children,  ...props}: MenuItemPrimitiveProps<object> & {  inset?: boolean  variant?: "default" | "destructive"}) {  return (    <MenuItemPrimitive      data-slot="context-menu-item"      data-inset={inset}      data-variant={variant}      textValue={typeof children === "string" ? children : props.textValue}      className={composeRenderProps(className, (className, { selectionMode }) =>        cn(contextMenuItemVariants({ selectionMode }), className)      )}      {...props}    >      {composeRenderProps(        children,        (children, { isSelected, selectionMode }) => (          <>            {selectionMode !== "none" ? (              <span                className="pointer-events-none absolute right-2"                data-slot={                  selectionMode === "single"                    ? "context-menu-radio-item-indicator"                    : "context-menu-checkbox-item-indicator"                }              >                {isSelected ? (                  <CheckIcon                  />                ) : null}              </span>            ) : null}            {children}          </>        )      )}    </MenuItemPrimitive>  )}
function ContextMenuSub({  ...props}: React.ComponentProps<typeof SubmenuTriggerPrimitive>) {  return <SubmenuTriggerPrimitive data-slot="context-menu-sub" {...props} />}
function ContextMenuSubTrigger({  className,  inset,  children,  ...props}: MenuItemPrimitiveProps<object> & {  inset?: boolean}) {  return (    <MenuItemPrimitive      data-slot="context-menu-sub-trigger"      data-inset={inset}      textValue={typeof children === "string" ? children : props.textValue}      className={cn(        "flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-8 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",        className      )}      {...props}    >      {composeRenderProps(children, (children) => (        <>          {children}          <ChevronRightIcon className="ml-auto" />        </>      ))}    </MenuItemPrimitive>  )}
function ContextMenuSubContent({  placement = "end top",  crossOffset = -3,  offset = 0,  className,  ...props}: React.ComponentProps<typeof ContextMenu>) {  return (    <ContextMenu      data-slot="context-menu-sub-content"      className={cn("w-auto min-w-32 rounded-md border bg-popover p-1 text-popover-foreground shadow-lg", className )}      placement={placement}      crossOffset={crossOffset}      offset={offset}      {...props}    />  )}
function ContextMenuSeparator({  className,  ...props}: React.ComponentProps<typeof SeparatorPrimitive>) {  return (    <SeparatorPrimitive      data-slot="context-menu-separator"      className={cn("-mx-1 my-1 h-px bg-border", className)}      {...props}    />  )}
function ContextMenuShortcut({  className,  ...props}: React.ComponentProps<"span">) {  return (    <span      data-slot="context-menu-shortcut"      className={cn(        "ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground",        className      )}      {...props}    />  )}
export {  ContextMenu,  ContextMenuTrigger,  ContextMenuItem,  ContextMenuLabel,  ContextMenuSeparator,  ContextMenuShortcut,  ContextMenuGroup,  ContextMenuSub,  ContextMenuSubContent,  ContextMenuSubTrigger,}

Usage

import { Pressable } from "react-aria-components"
import {  ContextMenu,  ContextMenuItem,  ContextMenuTrigger,} from "@/components/ui/context-menu"
<ContextMenuTrigger>  <Pressable>    <div role="button" aria-label="Order PO-2041, open the context menu">      Order PO-2041    </div>  </Pressable>  <ContextMenu>    <ContextMenuItem onAction={() => openOrder(order.id)}>Open</ContextMenuItem>    <ContextMenuItem>Duplicate</ContextMenuItem>  </ContextMenu></ContextMenuTrigger>

ContextMenuTrigger sets trigger="contextMenu" on the React Aria MenuTrigger. Its first child is the element that listens, wrapped in Pressable when it is not a React Aria component, and it needs an interactive role so that screen readers can announce it. The second child is the ContextMenu. Its parts follow the Dropdown Menu API, with the same React Aria props, and cannot be mixed with the Base UI parts of Menubar.

Examples

Checkboxes

Set selectionMode="multiple" on a ContextMenuGroup to make its items toggles. Give each item an id, and hold the state with selectedKeys and onSelectionChange.

Right click for flags

Radio

Set selectionMode="single" for a choice of one.

Owner: Luca

Destructive

variant="destructive" colours an item that removes data. Put it last, after a separator, and confirm with an Alert Dialog.

Tornival

Accessibility

KeyAction
MenuOpens the menu for the focused element, on keyboards that have a context menu key.
↓Moves focus to the next item.
↑Moves focus to the previous item.
→Opens the submenu of the focused item.
←Closes the submenu and returns focus to its item.
HomeMoves focus to the first item.
EndMoves focus to the last item.
EnterChooses the focused item.
SpaceChooses the focused item.
EscCloses the menu and returns focus to the trigger.

React Aria provides:

  • A menu that opens on a right click, on a long press on touch screens, and from the operating system and screen reader shortcuts for context menus.
  • The positioning of the menu at the point of the click.
  • The menu role, arrow key navigation, type-ahead and submenus, as in the dropdown menu.
  • Focus that moves into the menu and returns to the trigger on close.

You provide:

  • An interactive role and an accessible name on the element that listens.
  • Every action in the menu somewhere else too, because a right click is hidden from most users. Put the same actions in a Dropdown Menu next to the element, or on the page the element opens.
  • Text on every item. For an item with an icon and text, add textValue.

Guidelines

When to use

  • To add shortcuts for people who work with a pointer, on objects they act on often: rows, files, cards.
  • For actions that apply to the specific object under the pointer.

When not to use

  • As the only place for an action. Nothing tells the user that the menu is there. Use a Dropdown Menu with an icon trigger, and let the context menu repeat its items.
  • For an action on a screen that is mainly used by touch. A long press is easy to miss.
  • For the main action of an object. Show it as a Button.
  • For a bar of menus at the top of an app. Use a Menubar.

Content

  • Use the same items, in the same order and with the same wording, as the matching dropdown menu.
  • Start with a verb: "Open", "Duplicate", "Cancel order". Use sentence case, no full stop.
  • Put destructive items last, after a separator.
  • Name the element in its aria-label, so the announcement says what the menu is for.

Discoverability

Order PO-2041
Do

Offer the same actions from a visible button, and let the context menu be the shortcut.

Order PO-2041
Don’t

Don’t hide an action that people need, such as approving an order, in a context menu alone.

API reference

ContextMenuTrigger

Wraps the element and the menu through the React Aria MenuTrigger, with trigger="contextMenu" set. It accepts every MenuTrigger prop except trigger.

PropTypeDefaultDescription
childrenReactNodeNoneThe element that listens, then the ContextMenu.
isOpen?booleanNoneWhether the menu is open. Makes the menu controlled.
defaultOpen?booleanNoneWhether the menu is open on first render, when uncontrolled.
onOpenChange?(isOpen: boolean) => voidNoneCalled when the menu opens or closes.

ContextMenu

Renders a React Aria Popover that holds a Menu. It accepts every Menu prop and the props below.

PropTypeDefaultDescription
placement?Placement"bottom start"Where the menu opens relative to the point of the click.
offset?number4The distance in pixels from the point along the main axis.
crossOffset?number0The shift in pixels along the cross axis.
onAction?(key: Key) => voidNoneCalled with the id of the item that was chosen.
selectionMode?"none" | "single" | "multiple"NoneMakes every item selectable.
className?stringNoneClasses merged onto the popover. Use it to set the width.
children?ReactNodeNoneThe groups, items, separators and submenus.

ContextMenuGroup

Renders a React Aria MenuSection. It accepts every MenuSection prop, including selectionMode, selectedKeys, defaultSelectedKeys and onSelectionChange.

ContextMenuLabel

Renders a React Aria Header as a muted label for a group. inset indents it to line up with items that have a check mark or an icon.

ContextMenuItem

Renders a React Aria MenuItem. It accepts every MenuItem prop and the props below.

PropTypeDefaultDescription
variant?"default" | "destructive""default"A destructive item is coloured as a warning.
inset?booleanNoneIndents the item to line up with items that have a check mark or an icon.
id?KeyNoneThe identity of the item, used by onAction and by selection.
textValue?stringNoneThe text used for type-ahead. Set automatically when the children are a string.
onAction?() => voidNoneCalled when the item is chosen.
isDisabled?booleanNoneStops the item from being focused or chosen.

ContextMenuSeparator

Renders a React Aria Separator, a thin line between groups.

ContextMenuShortcut

A span that shows a shortcut at the end of an item. It displays the hint only: it does not register the key.

ContextMenuSub, ContextMenuSubTrigger and ContextMenuSubContent

ContextMenuSub wraps the React Aria SubmenuTrigger. ContextMenuSubTrigger is the MenuItem that opens the submenu and shows a chevron, and ContextMenuSubContent is its popover, which takes the props of ContextMenu with placement set to end top.