Context Menu
An accessible dropdown and context menu that is used to display a list of actions or options that a user can choose when a trigger element is right-clicked or long pressed.
Features
- Supports items, labels, groups of items
- Focus is fully managed using
aria-activedescendantpattern - Typeahead to allow focusing items by typing text
- Keyboard navigation support including arrow keys, home/end, page up/down
Installation
Install the menu package:
Anatomy
Check the menu anatomy and part names.
Each part includes a
data-partattribute to help identify them in the DOM.
Usage
Import the menu package:
import * as menu from "@zag-js/menu"
The menu package exports two key functions:
machine- Behavior logic for the menu.connect- Maps behavior to JSX props and event handlers.
Pass a unique
idtouseMachineso generated element ids stay predictable.
Then use the framework integration helpers:
To show the menu when a trigger element is right-clicked, use
api.getContextTriggerProps().
Context menus also open during a long-press of roughly 700ms when the pointer
is pen or touch.
Default open state
Use defaultOpen for an uncontrolled initial state.
const service = useMachine(menu.machine, { defaultOpen: true, })
Controlling open state
Use open and onOpenChange to control the open state.
const service = useMachine(menu.machine, { open, onOpenChange(details) { // details => { open: boolean } setOpen(details.open) }, })
Listening for highlighted items
Use onHighlightChange to react when keyboard or pointer highlight changes.
const service = useMachine(menu.machine, { onHighlightChange(details) { // details => { highlightedValue: string | null } console.log(details.highlightedValue) }, })
Listening for item selection
Use onSelect to react when an item is selected.
const service = useMachine(menu.machine, { onSelect(details) { // details => { value: string } console.log(details.value) }, })
Positioning the menu
Use positioning to configure menu placement.
const service = useMachine(menu.machine, { positioning: { placement: "right-start" }, })
Keeping the menu open after selection
Set closeOnSelect to false to keep the menu open after selecting an item.
const service = useMachine(menu.machine, { closeOnSelect: false, })
Styling guide
Each menu part includes a data-part attribute you can target in CSS.
Highlighted item state
When an item is highlighted, via keyboard navigation or pointer, it is given a
data-highlighted attribute.
[data-part="item"][data-highlighted] { /* styles for highlighted state */ } [data-part="item"][data-type="radio|checkbox"][data-highlighted] { /* styles for highlighted state */ }
Disabled item state
When an item or an option item is disabled, it is given a data-disabled
attribute.
[data-part="item"][data-disabled] { /* styles for disabled state */ } [data-part="item"][data-type="radio|checkbox"][data-disabled] { /* styles for disabled state */ }
Using arrows
When using arrows within the menu, you can style it using CSS variables.
[data-part="arrow"] { --arrow-size: 20px; --arrow-background: red; }
Checked option item state
When an option item is checked, it is given a data-state attribute.
[data-part="item"][data-type="radio|checkbox"][data-state="checked"] { /* styles for checked state */ }
Methods and Properties
Machine Context
The menu machine exposes the following context properties:
idsPartial<{ trigger: string; contextTrigger: string; content: string; groupLabel: (id: string) => string; group: (id: string) => string; positioner: string; arrow: string; }>The ids of the elements in the menu. Useful for composition.defaultHighlightedValuestringThe initial highlighted value of the menu item when rendered. Use when you don't need to control the highlighted value of the menu item.highlightedValuestringThe controlled highlighted value of the menu item.onHighlightChange(details: HighlightChangeDetails) => voidFunction called when the highlighted menu item changes.onSelect(details: SelectionDetails) => voidFunction called when a menu item is selected.anchorPointPointThe positioning point for the menu. Can be set by the context menu trigger or the button trigger.loopFocusbooleanWhether to loop the keyboard navigation.positioningPositioningOptionsThe options used to dynamically position the menucloseOnSelectbooleanWhether to close the menu when an option is selectedaria-labelstringThe accessibility label for the menuopenbooleanThe controlled open state of the menuonOpenChange(details: OpenChangeDetails) => voidFunction called when the menu opens or closesdefaultOpenbooleanThe initial open state of the menu when rendered. Use when you don't need to control the open state of the menu.typeaheadbooleanWhether the pressing printable characters should trigger typeahead navigationcompositebooleanWhether the menu is a composed with other composite widgets like a combobox or tabsnavigate(details: NavigateDetails) => voidFunction to navigate to the selected item if it's an anchor elementdir"ltr" | "rtl"The document's text/writing direction.idstringThe unique identifier of the machine.getRootNode() => ShadowRoot | Node | DocumentA root node to correctly resolve document in custom environments. E.x.: Iframes, Electron.onEscapeKeyDown(event: KeyboardEvent) => voidFunction called when the escape key is pressedonRequestDismiss(event: LayerDismissEvent) => voidFunction called when this layer is closed due to a parent layer being closedonPointerDownOutside(event: PointerDownOutsideEvent) => voidFunction called when the pointer is pressed down outside the componentonFocusOutside(event: FocusOutsideEvent) => voidFunction called when the focus is moved outside the componentonInteractOutside(event: InteractOutsideEvent) => voidFunction called when an interaction happens outside the component
Machine API
The menu api exposes the following methods:
openbooleanWhether the menu is opensetOpen(open: boolean) => voidFunction to open or close the menuhighlightedValuestringThe id of the currently highlighted menuitemsetHighlightedValue(value: string) => voidFunction to set the highlighted menuitemsetParent(parent: ParentMenuService) => voidFunction to register a parent menu. This is used for submenussetChild(child: ChildMenuService) => voidFunction to register a child menu. This is used for submenusreposition(options?: Partial<PositioningOptions>) => voidFunction to reposition the popovergetOptionItemState(props: OptionItemProps) => OptionItemStateReturns the state of the option itemgetItemState(props: ItemProps) => ItemStateReturns the state of the menu itemaddItemListener(props: ItemListenerProps) => VoidFunctionSetup the custom event listener for item selection event
Data Attributes
CSS Variables
Accessibility
Uses aria-activedescendant pattern to manage focus movement among menu items.
Keyboard Interactions
- SpaceActivates/Selects the highlighted item
- EnterActivates/Selects the highlighted item
- ArrowDownHighlights the next item in the menu
- ArrowUpHighlights the previous item in the menu
- ArrowRightArrowLeftWhen focus is on trigger, opens or closes the submenu depending on reading direction.
- EscCloses the context menu