Components
Context Menu
The menu that opens where the user right-clicks, or presses and holds, with the actions of what was clicked.
Introduction
A context menu opens at the pointer, with the actions of the thing that was clicked: copy a file, rename a row, delete a card. It is quick for people who know it is there, so the same actions should also be somewhere in the page for those who do not.
- Opens with a right click, with a press and hold on a touch screen, and with the Menu key or
Shift+F10on a keyboard. - Opens with its corner at the pointer, and turns to the other side when there is no room. It closes when the page scrolls.
- Items with an icon and the keys, links, disabled and dangerous items, titled sections, checkable items (checkboxes and a choice of one), and submenus.
- Built on react-aria's Menu and Popover, so the arrow keys, typeahead, focus and the screen reader announcements come from there.
The keys shown in an item are only shown: the menu does not listen for them. For a menu that a button opens, use a menu button, and for a list of commands to search, use the Command Menu.
Installation
centerUI has no CLI or registry yet: components are copied into your project.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxManual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
The panel and the items are those of the Menu, so they come from its files.
src/types/menu-styles.tsShow code
import { tv } from "tailwind-variants";
// Styles for Menu, and for ContextMenu, which has the same panel and items. `popover` gives the panel its small entrance animation
// (see globals.css).
export const menuStyles = tv({
slots: {
popover:
"popover z-50 max-w-[calc(100vw-1rem)] min-w-52 overflow-y-auto rounded-xl border bg-card p-1 text-card-fg shadow-lg",
menu: "flex flex-col outline-none",
section: "flex flex-col [&:not(:first-child)]:mt-1",
heading: "px-2.5 pt-1.5 pb-1 text-xs font-medium text-muted-fg",
item: [
"group/item flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none",
"data-focused:bg-muted data-pressed:bg-muted/70 data-open:bg-muted",
"data-disabled:cursor-not-allowed data-disabled:opacity-50",
"data-[variant=danger]:text-danger data-[variant=danger]:data-focused:bg-danger/10",
],
indicator:
"flex size-4 shrink-0 items-center justify-center text-fg [&_svg]:size-4",
description: "truncate text-xs font-normal text-muted-fg",
text: "flex min-w-0 flex-1 flex-col",
icon: "flex size-4 shrink-0 items-center justify-center text-muted-fg [&_svg]:size-4 group-data-[variant=danger]/item:text-current",
label: "min-w-0 flex-1 truncate",
shortcut:
"ml-6 flex shrink-0 items-center gap-1 font-sans text-xs text-muted-fg",
chevron: "ml-4 size-4 shrink-0 text-muted-fg",
separator: "-mx-1 my-1 h-px border-0 bg-border",
},
});src/types/context-menu-styles.tsShow code
import { tv } from "tailwind-variants";
// Styles for ContextMenu: the area that opens the menu. The panel and the items
// are those of Menu (see menu-styles.ts).
export const contextMenuStyles = tv({
slots: {
trigger:
"rounded-xl outline-none [-webkit-touch-callout:none] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
},
});2. Add the Menu and the Context Menu files
src/components/ui/menu/menu.tsxShow code
"use client";
import { type ReactNode, useId } from "react";
import {
Menu as AriaMenu,
MenuItem as AriaMenuItem,
type MenuProps as AriaMenuProps,
MenuSection as AriaMenuSection,
MenuTrigger as AriaMenuTrigger,
type MenuTriggerProps as AriaMenuTriggerProps,
type PopoverProps as AriaPopoverProps,
Header,
Popover,
Separator,
SubmenuTrigger,
} from "react-aria-components";
import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
} from "@/components/icons";
import { Button, type ButtonProps } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { menuStyles } from "@/types/menu-styles";
const styles = menuStyles();
export type MenuProps = AriaMenuTriggerProps;
/**
* A menu: a button that opens a list of actions. Use it for the actions that
* belong to one thing (a file, a row, an account) and would take too much room
* as buttons: rename, duplicate, delete. For a list to choose one value from,
* use a Select, and for one to search in, a Command Menu.
*
* Put a `MenuTrigger` (or any button) and a `MenuContent` with the items in it.
* Built on react-aria's Menu and Popover, so the arrow keys, typeahead, submenus,
* focus (into the menu, and back to the button when it closes) and the screen
* reader announcements come from there.
*
* @example
* <Menu>
* <MenuTrigger>Options</MenuTrigger>
* <MenuContent aria-label="Options">
* <MenuItem onAction={rename}>Rename</MenuItem>
* <MenuItem variant="danger" onAction={remove}>Delete</MenuItem>
* </MenuContent>
* </Menu>
*/
export function Menu(props: MenuProps) {
return <AriaMenuTrigger {...props} />;
}
export interface MenuTriggerProps extends Omit<ButtonProps, "children"> {
/** What the button says. Without text, use `isIcon` and give it an `aria-label`. */
children?: ReactNode;
/** A small arrow at the end, that says the button opens something. Defaults to `true` for a button with text. */
showChevron?: boolean;
}
/**
* The button that opens a `Menu`. It is a `Button`, so it takes its variants and
* sizes. It shows a small arrow unless it has only an icon.
*/
export function MenuTrigger({
children,
showChevron,
isIcon,
variant = "outline",
...props
}: MenuTriggerProps) {
const chevron = showChevron ?? !isIcon;
return (
<Button variant={variant} isIcon={isIcon} {...props}>
{children}
{chevron ? <ChevronDownIcon aria-hidden="true" /> : null}
</Button>
);
}
export interface MenuContentProps
extends Omit<
AriaMenuProps<object>,
"className" | "style" | "children" | "aria-label"
>,
Pick<
AriaPopoverProps,
"placement" | "offset" | "crossOffset" | "shouldFlip"
> {
/** `MenuItem`s, `MenuSection`s, `MenuSubmenu`s and `MenuSeparator`s. */
children: ReactNode;
/** Names the menu for screen readers, such as "File actions". */
"aria-label"?: string;
/** Make the panel at least as wide as the button. Defaults to `false`. */
matchTriggerWidth?: boolean;
className?: string;
}
/**
* The panel of a `Menu`: it opens next to the button, and turns to the other
* side when there is not room. Arrow keys move, a letter jumps to an item, Enter
* runs it, and Escape closes it.
*/
export function MenuContent({
children,
"aria-label": ariaLabel = "Menu",
placement = "bottom start",
offset = 6,
crossOffset,
shouldFlip,
matchTriggerWidth = false,
className,
...props
}: MenuContentProps) {
return (
<Popover
placement={placement}
offset={offset}
crossOffset={crossOffset}
shouldFlip={shouldFlip}
className={cn(
styles.popover(),
matchTriggerWidth && "min-w-(--trigger-width)",
className,
)}
>
<AriaMenu {...props} aria-label={ariaLabel} className={styles.menu()}>
{children}
</AriaMenu>
</Popover>
);
}
export interface MenuItemProps {
/** What the item is called. */
children: ReactNode;
/** Runs when the item is chosen, by Enter or by a press. */
onAction?: () => void;
/** An icon before the name. */
icon?: ReactNode;
/** A second, smaller line under the name. */
description?: ReactNode;
/** The keys of the action, shown at the end of the row, such as `"⌘ C"`. They are only shown: the item does not listen for them. */
shortcut?: string;
/** Red, for an action that destroys something. */
variant?: "default" | "danger";
/** Makes it a link to this address instead of running a function. */
href?: string;
/** The text a typed letter is matched to and a screen reader says, when the name is not text. Defaults to the name. */
textValue?: string;
/** Close the menu after the item is chosen. Defaults to `true`, and to `false` for an item that can be checked. */
closeOnAction?: boolean;
isDisabled?: boolean;
/** A stable name for it. Needed for an item in a section that can be checked, as it is what `selectedKeys` holds. */
id?: string;
}
function ShortcutKeys({ shortcut }: { shortcut: string }) {
// A span, not react-aria's Keyboard: that says the item has a shortcut of its
// own to assistive technology, and these keys are only shown.
return <span className={styles.shortcut()}>{shortcut}</span>;
}
/**
* One action in the menu: a name, and if you like an icon and the keys. In a
* `MenuSection` that can be checked, it shows a check while it is on.
*/
export function MenuItem({
children,
onAction,
icon,
description,
shortcut,
variant = "default",
href,
textValue,
closeOnAction,
isDisabled,
id,
}: MenuItemProps) {
// An item keeps one id for as long as it is there, even when its name changes.
const generatedId = useId();
return (
<AriaMenuItem
id={id ?? generatedId}
href={href}
isDisabled={isDisabled}
textValue={
textValue ?? (typeof children === "string" ? children : undefined)
}
shouldCloseOnSelect={closeOnAction}
data-variant={variant}
onAction={onAction}
className={styles.item()}
>
{({ selectionMode, isSelected, hasSubmenu }) => (
<>
{selectionMode !== "none" ? (
<span aria-hidden="true" className={styles.indicator()}>
{isSelected ? (
selectionMode === "single" ? (
<span className="size-1.5 rounded-full bg-current" />
) : (
<CheckIcon />
)
) : null}
</span>
) : null}
{icon ? (
<span aria-hidden="true" className={styles.icon()}>
{icon}
</span>
) : null}
{description ? (
<span className={styles.text()}>
<span className={styles.label()}>{children}</span>
<span className={styles.description()}>{description}</span>
</span>
) : (
<span className={styles.label()}>{children}</span>
)}
{shortcut ? <ShortcutKeys shortcut={shortcut} /> : null}
{hasSubmenu ? (
<ChevronRightIcon aria-hidden="true" className={styles.chevron()} />
) : null}
</>
)}
</AriaMenuItem>
);
}
export interface MenuSectionProps {
/** The title of the group, such as "View". */
heading?: string;
/** `MenuItem`s. */
children: ReactNode;
/**
* Whether its items can be checked: `multiple` for checkboxes, `single` for
* a choice of one (radios). Give each item an `id`. Defaults to `none`.
*/
selectionMode?: "none" | "single" | "multiple";
/** The ids of the checked items, for a controlled section. */
selectedKeys?: Iterable<string>;
/** The ids of the items checked at first, for an uncontrolled one. */
defaultSelectedKeys?: Iterable<string>;
/** Called with the ids of the checked items when one is checked or unchecked. */
onSelectionChange?: (keys: Set<string>) => void;
/** Names the group for screen readers when it has no `heading`. */
"aria-label"?: string;
}
/**
* A titled group of items. With a `selectionMode` its items can be checked, as
* a set of options that stay on or off, or as a choice of one.
*/
export function MenuSection({
heading,
children,
selectionMode,
selectedKeys,
defaultSelectedKeys,
onSelectionChange,
"aria-label": ariaLabel,
}: MenuSectionProps) {
return (
<AriaMenuSection
aria-label={heading ? undefined : ariaLabel}
selectionMode={selectionMode}
selectedKeys={selectedKeys}
defaultSelectedKeys={defaultSelectedKeys}
onSelectionChange={
onSelectionChange
? (keys) =>
// "all" only comes from a select-all key, which a menu does not have.
onSelectionChange(
keys === "all" ? new Set() : (keys as Set<string>),
)
: undefined
}
className={styles.section()}
>
{heading ? <Header className={styles.heading()}>{heading}</Header> : null}
{children}
</AriaMenuSection>
);
}
export interface MenuSubmenuProps {
/** What the item that opens the submenu says. */
label: ReactNode;
/** An icon before the label. */
icon?: ReactNode;
/** The text a typed letter is matched to, when the label is not text. */
textValue?: string;
/** The items of the submenu. */
children: ReactNode;
isDisabled?: boolean;
/** A stable name for it. */
id?: string;
/** Names the submenu for screen readers. Defaults to the label. */
"aria-label"?: string;
}
/**
* An item that opens another menu to its side, on hover or with the right arrow
* key. Its items are `MenuItem`s, and it can hold sections and other
* submenus.
*/
export function MenuSubmenu({
label,
icon,
textValue,
children,
isDisabled,
id,
"aria-label": ariaLabel,
}: MenuSubmenuProps) {
const generatedId = useId();
const name = textValue ?? (typeof label === "string" ? label : undefined);
return (
<SubmenuTrigger>
<MenuItem
id={id ?? generatedId}
icon={icon}
textValue={name}
isDisabled={isDisabled}
>
{label}
</MenuItem>
<Popover offset={-4} className={styles.popover()}>
<AriaMenu
aria-label={ariaLabel ?? name ?? "Submenu"}
onContextMenu={(event) => event.preventDefault()}
className={styles.menu()}
>
{children}
</AriaMenu>
</Popover>
</SubmenuTrigger>
);
}
/** A line between two groups. */
export function MenuSeparator() {
return <Separator className={styles.separator()} />;
}src/components/ui/context-menu/context-menu.tsxShow code
"use client";
import {
createContext,
type HTMLAttributes,
type KeyboardEvent,
type MouseEvent,
type PointerEvent,
type ReactNode,
useContext,
useEffect,
useRef,
useState,
} from "react";
import {
Button as AriaButton,
Menu,
MenuTrigger,
Popover,
} from "react-aria-components";
import { cn } from "@/lib/cn";
import { contextMenuStyles } from "@/types/context-menu-styles";
import { menuStyles } from "@/types/menu-styles";
interface ContextMenuState {
restoreFocus: () => void;
isOpen: boolean;
setOpen: (isOpen: boolean) => void;
point: { x: number; y: number };
openAt: (x: number, y: number) => void;
}
const ContextMenuContext = createContext<ContextMenuState | null>(null);
function useContextMenu(name: string) {
const context = useContext(ContextMenuContext);
if (!context) throw new Error(`${name} must be used inside a ContextMenu.`);
return context;
}
const styles = contextMenuStyles();
const menuClasses = menuStyles();
export interface ContextMenuProps {
/** A `ContextMenuTrigger` (the area) and a `ContextMenuContent` (the menu). */
children: ReactNode;
/** Called when the menu opens or closes. */
onOpenChange?: (isOpen: boolean) => void;
}
/**
* A context menu: the menu that opens where the user right-clicks, or presses
* and holds on a touch screen, or presses the Menu key or Shift+F10 on a
* keyboard. Use it for the actions of the thing that was clicked: a file, a row,
* a card, a spot on a canvas. It is a shortcut to those actions, so they should
* be somewhere else in the interface too.
*
* Put a `ContextMenuTrigger` around the area, and a `ContextMenuContent` with
* the items next to it. The menu is built on react-aria's Menu and Popover, so
* the arrow keys, typeahead, submenus, focus (into the menu, and back to where
* it was when the menu closes) and the screen reader announcements come from
* there.
*
* @example
* <ContextMenu>
* <ContextMenuTrigger className="p-8">Right-click here</ContextMenuTrigger>
* <ContextMenuContent aria-label="Actions">
* <ContextMenuItem onAction={copy}>Copy</ContextMenuItem>
* <ContextMenuItem variant="danger" onAction={remove}>Delete</ContextMenuItem>
* </ContextMenuContent>
* </ContextMenu>
*/
export function ContextMenu({ children, onOpenChange }: ContextMenuProps) {
const [isOpen, setIsOpen] = useState(false);
const [point, setPoint] = useState({ x: 0, y: 0 });
// Where the focus was when the menu opened, so it goes back there when it closes.
const returnFocus = useRef<HTMLElement | null>(null);
const onOpenChangeRef = useRef(onOpenChange);
onOpenChangeRef.current = onOpenChange;
function setOpen(next: boolean) {
setIsOpen(next);
onOpenChangeRef.current?.(next);
}
const setOpenRef = useRef(setOpen);
setOpenRef.current = setOpen;
function openAt(x: number, y: number) {
if (!isOpen && document.activeElement instanceof HTMLElement)
returnFocus.current = document.activeElement;
setPoint({ x, y });
setOpen(true);
}
// Called when the menu is gone. The focus is then nowhere, on the page, and goes
// back where it was. If the user has put it somewhere else (clicked into a
// field to close the menu), it stays there.
function restoreFocus() {
setTimeout(() => {
const active = document.activeElement;
const target = returnFocus.current;
if (target?.isConnected && (!active || active === document.body))
target.focus({ preventScroll: true });
}, 0);
}
// The menu closes when the page scrolls, as the menu of the system does: it
// stays where the pointer was, and that is not where the thing is now.
useEffect(() => {
if (!isOpen) return;
const close = () => setOpenRef.current(false);
window.addEventListener("scroll", close, true);
return () => window.removeEventListener("scroll", close, true);
}, [isOpen]);
return (
<ContextMenuContext.Provider
value={{ isOpen, setOpen, point, openAt, restoreFocus }}
>
{children}
</ContextMenuContext.Provider>
);
}
export interface ContextMenuTriggerProps
extends Omit<
HTMLAttributes<HTMLDivElement>,
"onContextMenu" | "onKeyDown" | "onPointerDown"
> {
/** Turns it off: the menu of the browser opens as it would without it. Defaults to `false`. */
isDisabled?: boolean;
/**
* How long a finger is held down to open the menu on a touch screen, in
* milliseconds. Defaults to `500`.
*/
longPressDelay?: number;
/**
* Whether the area can be reached with Tab, so that the menu can be opened with
* the Menu key or Shift+F10 from a keyboard. Turn it off if the area has
* something inside it that can be. Defaults to `true`.
*/
isFocusable?: boolean;
}
/**
* The area that opens the menu. It is a plain `div`: give it a size and a look
* with `className`, and put what the menu is for inside.
*/
export function ContextMenuTrigger({
isDisabled = false,
longPressDelay = 500,
isFocusable = true,
className,
children,
...props
}: ContextMenuTriggerProps) {
const { openAt } = useContextMenu("ContextMenuTrigger");
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const start = useRef({ x: 0, y: 0 });
const lastKey = useRef(0);
useEffect(() => () => clearTimeout(timer.current), []);
function onContextMenu(event: MouseEvent<HTMLDivElement>) {
if (isDisabled) return;
// The key already opened it, and the browser says so again.
if (performance.now() - lastKey.current < 300) {
event.preventDefault();
return;
}
event.preventDefault();
// The innermost area answers, not the ones around it.
event.stopPropagation();
openAt(event.clientX, event.clientY);
}
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
if (isDisabled || event.defaultPrevented) return;
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10"))
return;
event.preventDefault();
event.stopPropagation();
lastKey.current = performance.now();
const rect = (event.target as Element).getBoundingClientRect();
openAt(rect.left + rect.width / 2, rect.top + rect.height / 2);
}
function onPointerDown(event: PointerEvent<HTMLDivElement>) {
if (isDisabled || event.pointerType !== "touch") return;
start.current = { x: event.clientX, y: event.clientY };
clearTimeout(timer.current);
timer.current = setTimeout(
() => openAt(start.current.x, start.current.y),
longPressDelay,
);
}
function onPointerMove(event: PointerEvent<HTMLDivElement>) {
if (
Math.hypot(
event.clientX - start.current.x,
event.clientY - start.current.y,
) > 10
)
clearTimeout(timer.current);
}
const cancel = () => clearTimeout(timer.current);
return (
// biome-ignore lint/a11y/noStaticElementInteractions: the area has no role of its own, as it is whatever the app puts in it; the menu is opened with a right click, a long press, or the Menu key on it
<div
tabIndex={isFocusable && !isDisabled ? 0 : undefined}
{...props}
className={cn(styles.trigger(), className)}
onContextMenu={onContextMenu}
onKeyDown={onKeyDown}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={cancel}
onPointerCancel={cancel}
>
{children}
</div>
);
}
// Runs a function when it is taken off the page: the menu is removed after it
// has closed, and when it has, this is.
function OnUnmount({ run }: { run: () => void }) {
const latest = useRef(run);
latest.current = run;
useEffect(() => () => latest.current(), []);
return null;
}
export interface ContextMenuContentProps {
/** `ContextMenuItem`s, `ContextMenuSection`s, `ContextMenuSubmenu`s and `ContextMenuSeparator`s. */
children: ReactNode;
/** Names the menu for screen readers, such as "File actions". */
"aria-label"?: string;
className?: string;
}
/**
* The menu: it opens with its corner at the pointer, and turns to the other side
* when there is not room. Arrow keys move, a letter jumps to an item, Enter runs
* it, and Escape closes it.
*/
export function ContextMenuContent({
children,
"aria-label": ariaLabel = "Context menu",
className,
}: ContextMenuContentProps) {
const { isOpen, setOpen, point, restoreFocus } =
useContextMenu("ContextMenuContent");
const anchor = useRef<HTMLButtonElement>(null);
return (
<MenuTrigger isOpen={isOpen} onOpenChange={setOpen}>
{/* A point where the pointer was: the menu is placed by it. It is a button
so that the menu has a trigger, as react-aria expects, but it is never
pressed: it has no size, is hidden, and lets the pointer through. */}
<AriaButton
ref={anchor}
aria-hidden="true"
excludeFromTabOrder
className="pointer-events-none fixed size-0 overflow-hidden opacity-0"
// A little away from the pointer, so that the item under it is not the
// one that lets go of the button.
style={{ left: point.x + 3, top: point.y + 3 }}
/>
<Popover
// A right click somewhere else while it is open does not close it: it
// opens again there, as a new menu, so that it is placed at the new point.
key={`${point.x},${point.y}`}
triggerRef={anchor}
placement="bottom start"
className={cn(menuClasses.popover(), className)}
>
<Menu
aria-label={ariaLabel}
onContextMenu={(event) => event.preventDefault()}
className={menuClasses.menu()}
>
{children}
</Menu>
<OnUnmount run={restoreFocus} />
</Popover>
</MenuTrigger>
);
}
// The items are those of Menu: a context menu and a menu hold the same things.
export {
MenuItem as ContextMenuItem,
type MenuItemProps as ContextMenuItemProps,
MenuSection as ContextMenuSection,
type MenuSectionProps as ContextMenuSectionProps,
MenuSeparator as ContextMenuSeparator,
MenuSubmenu as ContextMenuSubmenu,
type MenuSubmenuProps as ContextMenuSubmenuProps,
} from "@/components/ui/menu/menu";3. Use it
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSection,
ContextMenuSeparator,
ContextMenuSubmenu,
ContextMenuTrigger,
} from "@/components/ui/context-menu/context-menu";Anatomy
An area, and a menu next to it.
<ContextMenu>
<ContextMenuTrigger className="p-8">Right-click here</ContextMenuTrigger>
<ContextMenuContent aria-label="File actions">
<ContextMenuItem icon={<CopyIcon />} shortcut="⌘ D">Duplicate</ContextMenuItem>
<ContextMenuSubmenu label="Move to">
<ContextMenuItem>Inbox</ContextMenuItem>
</ContextMenuSubmenu>
<ContextMenuSeparator />
<ContextMenuItem variant="danger">Delete</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>| Part | Rendered as | Notes |
|---|---|---|
| ContextMenu | - | Holds the open state and where the pointer was. It has no look of its own. |
| ContextMenuTrigger | div | The area the menu is for. It listens for the right click, the press and hold, and the Menu key. |
| ContextMenuContent | menu | The panel with the items. It opens with its corner at the pointer, and turns to the other side when there is no room. |
| ContextMenuItem | menu item | One action: a name, and if you like an icon and the keys. |
| ContextMenuSection | menu section | A titled group of items. It can make its items checkable. |
| ContextMenuSubmenu | menu item | An item that opens another menu to its side. |
| ContextMenuSeparator | separator | A line between two groups. |
Keyboard
The area can be reached with Tab, so the menu is open to people who do not use a mouse.
| Key | What it does |
|---|---|
| Menu key, or Shift+F10 | On the area, opens the menu. |
| ↓ ↑ | Moves to the next or the previous item. |
| → | On an item with a submenu, opens it. |
| ← | In a submenu, closes it. |
| A letter | Jumps to the item that starts with what is typed. |
| Enter or Space | Runs the item, or checks it. |
| Escape | Closes the menu, and focus goes back to the area. |
Examples
Usage
Right-click the area, or press and hold it on a touch screen.
Last action: nothing yet
Items
An item can have an icon and the keys of its action. It can be disabled, a link, or dangerous.
Sections
A heading and a line between groups make a long menu easier to read.
Checkable items
selectionMode makes the items of a section checkable: multiple for options that stay on or off, single for a choice of one. Give each item an id, which is what selectedKeys holds. Choosing a checkable item leaves the menu open.
Show: grid, rulers · Sort: name
A menu for each row
Put a ContextMenu in each row of a list, and its actions know which row they are for.
- design-system.fig
- invoice-0421.pdf
- team-photo.png
Last action: nothing yet
Disabled
isDisabled leaves the area alone, and the menu of the browser opens as it would without it.
Component API
ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSection and ContextMenuSubmenu take these props.
ContextMenu
| Prop | Type | Default |
|---|---|---|
| children | ReactNode | - |
| onOpenChange | (isOpen: boolean) => void | - |
ContextMenuTrigger
| Prop | Type | Default |
|---|---|---|
| isDisabled | boolean | false |
| longPressDelay | number (ms) | 500 |
| isFocusable | boolean | true |
| className | string | - |
| …rest | HTML attributes of a div | - |
ContextMenuContent
| Prop | Type | Default |
|---|---|---|
| aria-label | string | "Context menu" |
| className | string | - |
ContextMenuItem
| Prop | Type | Default |
|---|---|---|
| children | ReactNode | - |
| onAction | () => void | - |
| icon | ReactNode | - |
| description | ReactNode | - |
| shortcut | string | - |
| variant | "default" | "danger" | "default" |
| href | string | - |
| textValue | string | the name |
| closeOnAction | boolean | true |
| isDisabled | boolean | false |
| id | string | made up |
ContextMenuSection
| Prop | Type | Default |
|---|---|---|
| heading | string | - |
| selectionMode | "none" | "single" | "multiple" | "none" |
| selectedKeys | Iterable<string> | - |
| defaultSelectedKeys | Iterable<string> | - |
| onSelectionChange | (keys: Set<string>) => void | - |
| aria-label | string | - |
ContextMenuSubmenu
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - |
| icon | ReactNode | - |
| textValue | string | the label |
| isDisabled | boolean | false |
| id | string | made up |
| aria-label | string | the label |