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-menuTo copy the component by hand, install its dependencies:
pnpm add react-aria-components class-variance-authority cn lucide-reactThen copy the source into 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.
Radio
Set selectionMode="single" for a choice of one.
Destructive
variant="destructive" colours an item that removes data. Put it last, after a separator, and confirm with an Alert Dialog.
Accessibility
| Key | Action |
|---|---|
| Menu | Opens 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. |
| Home | Moves focus to the first item. |
| End | Moves focus to the last item. |
| Enter | Chooses the focused item. |
| Space | Chooses the focused item. |
| Esc | Closes 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
menurole, 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
Offer the same actions from a visible button, and let the context menu be the shortcut.
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.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | None | The element that listens, then the ContextMenu. |
isOpen? | boolean | None | Whether the menu is open. Makes the menu controlled. |
defaultOpen? | boolean | None | Whether the menu is open on first render, when uncontrolled. |
onOpenChange? | (isOpen: boolean) => void | None | Called 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.
| Prop | Type | Default | Description |
|---|---|---|---|
placement? | Placement | "bottom start" | Where the menu opens relative to the point of the click. |
offset? | number | 4 | The distance in pixels from the point along the main axis. |
crossOffset? | number | 0 | The shift in pixels along the cross axis. |
onAction? | (key: Key) => void | None | Called with the id of the item that was chosen. |
selectionMode? | "none" | "single" | "multiple" | None | Makes every item selectable. |
className? | string | None | Classes merged onto the popover. Use it to set the width. |
children? | ReactNode | None | The 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.
| Prop | Type | Default | Description |
|---|---|---|---|
variant? | "default" | "destructive" | "default" | A destructive item is coloured as a warning. |
inset? | boolean | None | Indents the item to line up with items that have a check mark or an icon. |
id? | Key | None | The identity of the item, used by onAction and by selection. |
textValue? | string | None | The text used for type-ahead. Set automatically when the children are a string. |
onAction? | () => void | None | Called when the item is chosen. |
isDisabled? | boolean | None | Stops 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.