Skip to main content
0.39.0
View Zag.js on Github
Join the Discord server

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

  • Support for items, labels, groups of items.
  • Focus is fully managed using aria-activedescendant pattern.
  • Typeahead to allow focusing items by typing text.
  • Keyboard navigation support including arrow keys, home/end, page up/down.

Installation

To use the menu machine in your project, run the following command in your command line:

npm install @zag-js/menu @zag-js/react # or yarn add @zag-js/menu @zag-js/react

This command will install the framework agnostic menu logic and the reactive utilities for your framework of choice.

Anatomy

To set up the menu correctly, you'll need to understand its anatomy and how we name its parts.

Each part includes a data-part attribute to help identify them in the DOM.

Usage

First, import the menu package into your project

import * as menu from "@zag-js/menu"

The menu package exports two key functions:

  • machine — The state machine logic for the menu widget.
  • connect — The function that translates the machine's state to JSX attributes and event handlers.

You'll need to provide a unique id to the useMachine hook. This is used to ensure that every part has a unique identifier.

Next, import the required hooks and functions for your framework and use the menu machine in your project 🔥

To show the menu when a trigger element is right-clicked, use the contextTriggerProps provided by the menu's connect function.

Context menu's are also opened during a long-press of roughly 700ms when the pointer is pen or touch.

import * as menu from "@zag-js/menu" import { useMachine, normalizeProps } from "@zag-js/react" export function ContextMenu() { const [state, send] = useMachine( menu.machine({ id:'1', "aria-label": "File", }), ) const api = menu.connect(state, send, normalizeProps) return ( <div> <div {...api.contextTriggerProps}> <div>Open context menu</div> </div> <div {...api.positionerProps}> <ul {...api.contentProps}> <li {...api.getItemProps({ id: "edit" })}>Edit</li> <li {...api.getItemProps({ id: "duplicate" })}>Duplicate</li> <li {...api.getItemProps({ id: "delete" })}>Delete</li> <li {...api.getItemProps({ id: "export" })}>Export...</li> </ul> </div> </div> ) }

Styling guide

Earlier, we mentioned that each menu part has a data-part attribute added to them to select and style them in the DOM.

Focused item state

When an item is focused, via keyboard navigation or pointer, it is given a data-focus attribute.

[data-part="item"][data-focus] { /* styles for focused state */ } [data-part="option-item"][data-focus] { /* styles for focused 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="option-item"][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-checked attribute.

[data-part="option-item"][data-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; label(id: string): string; group(id: string): string; positioner: string; arrow: string; }>The ids of the elements in the menu. Useful for composition.
  • valueRecord<string, string | string[]>The values of radios and checkboxes in the menu.
  • onValueChange(details: ValueChangeDetails) => voidCallback to be called when the menu values change (for radios and checkboxes).
  • highlightedIdstringThe `id` of the active menu item.
  • 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.
  • loopbooleanWhether to loop the keyboard navigation.
  • positioningPositioningOptionsThe options used to dynamically position the menu
  • closeOnSelectbooleanWhether to close the menu when an option is selected
  • aria-labelstringThe accessibility label for the menu
  • openbooleanWhether the menu is open
  • onOpenChange(details: OpenChangeDetails) => voidFunction called when the menu opens or closes
  • open.controlledbooleanWhether the menu's open state is controlled by the user
  • dir"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 pressed
  • onPointerDownOutside(event: PointerDownOutsideEvent) => voidFunction called when the pointer is pressed down outside the component
  • onFocusOutside(event: FocusOutsideEvent) => voidFunction called when the focus is moved outside the component
  • onInteractOutside(event: InteractOutsideEvent) => voidFunction called when an interaction happens outside the component

Machine API

The menu api exposes the following methods:

  • isOpenbooleanWhether the menu is open
  • open() => voidFunction to open the menu
  • close() => voidFunction to close the menu
  • highlightedIdstringThe id of the currently highlighted menuitem
  • setHighlightedId(id: string) => voidFunction to set the highlighted menuitem
  • setParent(parent: Service) => voidFunction to register a parent menu. This is used for submenus
  • setChild(child: Service) => voidFunction to register a child menu. This is used for submenus
  • valueRecord<string, string | string[]>The value of the menu options item
  • setValue(name: string, value: any) => voidFunction to set the value of the menu options item
  • reposition(options?: Partial<PositioningOptions>) => voidFunction to reposition the popover
  • getOptionItemState(props: OptionItemProps) => OptionItemStateReturns the state of the option item
  • getItemState(props: ItemProps) => ItemStateReturns the state of the menu item

Accessibility

Uses aria-activedescendant pattern to manage focus movement among menu items.

Keyboard Interactions

  • Space
    Activates/Selects the highlighted item
  • Enter
    Activates/Selects the highlighted item
  • ArrowDown
    Highlights the next item in the menu
  • ArrowUp
    Highlights the previous item in the menu
  • ArrowRightArrowLeft
    When focus is on trigger, opens or closes the submenu depending on reading direction.
  • Esc
    Closes the context menu

Edit this page on GitHub

On this page