useContextMenu

Handles context menu events across mouse, touch, keyboard, and screen reader interactions.

Right click here
    import React from 'react';
    import {useContextMenu} from 'react-aria/useContextMenu';
    
    function Example() {
      let [events, setEvents] = React.useState<string[]>([]);
    
      let {contextMenuProps} = useContextMenu({
        onContextMenu: e => setEvents(
          events => [`context menu at (${e.x}, ${e.y})`, ...events]
        )
      });
    
      return (
        <>
          <div
            {...contextMenuProps}
            tabIndex={0}
            style={{
              width: 250,
              height: 100,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              border: '2px dashed gray',
              borderRadius: 10
            }}>
            Right click here
          </div>
          <ul
            style={{
              maxHeight: '200px',
              overflow: 'auto'
            }}>
            {events.map((e, i) => <li key={i}>{e}</li>)}
          </ul>
        </>
      );
    }
    

    Features

    There is no standard way to trigger a context menu consistently across platforms, input devices, and assistive technologies. useContextMenu normalizes these differences into a single onContextMenu event.

    • Handles mouse right click and Control + click on macOS
    • Handles long press on touch devices, including iOS where the contextmenu event does not fire
    • Handles keyboard shortcuts such as Shift + F10 on Windows and Linux, and Control + Enter on macOS
    • Handles screen reader specific gestures such as VoiceOver's context menu command
    • Prevents the browser and OS context menus from appearing
    • Reports the position the menu should be displayed relative to the target element

    Anatomy

    useContextMenu returns props that you spread onto the element that should respond to context menu interactions. The onContextMenu handler is called with a ContextMenuEvent that includes the target element and the x and y position where the menu should appear, relative to the target.

    import {useContextMenu} from 'react-aria/useContextMenu';
    
    let {contextMenuProps} = useContextMenu(props);
    

    API

    useContextMenu(props: ):

    ContextMenuProps

    NameType

    ContextMenuAria

    NameType
    contextMenuPropsHTMLAttributes<HTMLElement>

    Props to spread on the target element.

    ContextMenuEvent

    The onContextMenu handler is fired with a ContextMenuEvent, which exposes the target element and the position the menu should be displayed relative to it.

    NameType
    xnumber

    X position relative to the target.

    ynumber

    Y position relative to the target.