MenuTrigger and Menu

The MenuTrigger serves as a wrapper around a Menu and its associated trigger, linking the Menu's open state with the trigger's press state.

The Menu allow users to choose from a list of options which can change based on the content. Menus are used to display transient content such as options, additional actions, and more. They stand out visually through stroke and drop shadow and float on top of the interface.

installyarn add @react-spectrum/menu
version3.0.0-alpha.1
usageimport {Menu, MenuTrigger} from '@react-spectrum/menu'

Example#


<MenuTrigger>
  <ActionButton>
      Edit
  </ActionButton>
  <Menu>
    <Item>Cut</Item>
    <Item>Copy</Item>
    <Item>Paste</Item>
  </Menu>
</MenuTrigger>

Content#


The Menu accepts Items and Sections as children. Items can be statically populated (initial example above) or dynamically (below). The dynamic method would be better suited to use if the actions within a Menu came from a data object such as values returned via an API call. The uniqueKey prop needs to be set on an Item when statically defining Items and the itemKey prop in the Menu when its Items are dynamically populated.

<MenuTrigger>
  <ActionButton>
      Edit
  </ActionButton>
  <Menu
    items={[{name: 'Cut'}, {name: 'Copy'}, {name: 'Paste'}]}
    itemKey="name">
    {item => <Item>{item.name}</Item>}
  </Menu>
</MenuTrigger>

The MenuTrigger accepts exactly two children: the Menu and the element which triggers the opening of the Menu. The trigger must be the first child passed into the MenuTrigger and should be an element that supports press events.

If the Menu is open within a MenuTrigger it will close on blur or scroll events.

Selection#

Changes to the Menu's selected Item are propagated via the event onAction.

The defaultSelectedKeys prop can be used to preselect Menu Items in the Menu placing selection of a Menu in an uncontrolled state. Alternatively, the selectedKeys prop preselects an Item in the Menu placing Item selection in a controlled state.

<MenuTrigger closeOnSelect={false}>
  <ActionButton>
      Edit (Controlled)
  </ActionButton>
  <Menu selectionMode="single" selectedKeys={['copy']}>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger closeOnSelect={false}>
  <ActionButton>
      Edit (Uncontrolled)
  </ActionButton>
  <Menu selectionMode="single" defaultSelectedKeys={['paste']}>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

The selectionMode prop specifies how many Menu Items can be selected, with the options being a single Menu Item, multiple Menu Items, or disabling selection entirely (default).

<MenuTrigger closeOnSelect={false}>
  <ActionButton>
      Show (Multiple)
  </ActionButton>
  <Menu selectionMode="multiple" defaultSelectedKeys={['Sidebar', 'Console']}>
    <Item uniqueKey='Sidebar'>Sidebar</Item>
    <Item uniqueKey='Searchbar'>Searchbar</Item>
    <Item uniqueKey='Tools'>Tools</Item>
    <Item uniqueKey='Console'>Console</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger closeOnSelect={false}>
  <ActionButton>
      Edit (Selection Mode None)
  </ActionButton>
  <Menu selectionMode="none">
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

Sections#

Menus may have Sections which can be used to wrap groups of Items. Each Section takes a title and uniqueKey prop.

Static Items

<MenuTrigger>
  <ActionButton>
      Edit
  </ActionButton>
  <Menu>
    <Section uniqueKey="rollback" title="Rollback Options">
      <Item uniqueKey="undo">Undo</Item>
      <Item uniqueKey="redo">Redo</Item>
    </Section>
    <Section uniqueKey="select" title="Selected Text Options">
      <Item uniqueKey="cut">Cut</Item>
      <Item uniqueKey="copy">Copy</Item>
      <Item uniqueKey="paste">Paste</Item>
    </Section>
  </Menu>
</MenuTrigger>

Dynamic Items

Sections should be populated with dynamic Items from a hierarchical data structure. Section takes an array of data using the items prop.

<MenuTrigger>
  <ActionButton>
      File Types
  </ActionButton>
  <Menu
    items={[{name: 'Docs', children: [{name: 'PDF'}]}, {name: 'Images', children: [{name: 'jpeg'}, {name: 'png'}, {name: 'tiff'}]}]}
    itemKey="name">
    {item => (
      <Section items={item.children} title={item.name}>
        {item => <Item>{item.name}</Item>}
      </Section>
    )}
  </Menu>
</MenuTrigger>

Complex Menu Items#

A Menu Item's content may be any renderable node, not just strings.

View guidelines

import {Keyboard, Text} from '@react-spectrum/typography';

<MenuTrigger>
  <ActionButton>
      Edit
  </ActionButton>
  <Menu
    itemKey="name"
    items={[
      {name: 'Copy', icon: 'Copy', shortcut: '⌘C'},
      {name: 'Cut', icon: 'Cut', shortcut: '⌘X'},
      {name: 'Paste', icon: 'Paste', shortcut: '⌘V'}
    ]}>
    {item => {
      let iconMap = {
        Copy,
        Cut,
        Paste
      };
      let Icon = iconMap[item.icon];
      return (
        <Item childItems={item.children} textValue={item.name}>
          <Icon size="S" />
          <Text>{item.name}</Text>
          <Keyboard>{item.shortcut}</Keyboard>
        </Item>
      );
    }}
  </Menu>
</MenuTrigger>

Internationalization#

To internationalize a Menu, a localized string should be passed to the children prop of each Menu Item or to a Section's title prop. For languages that are read right to left (e.g. Hebrew and Arabic), the layout of the Menu is flipped.

Accessibility#

Titleless Menu Sections must be provided with an aria-label for accessibility.

<MenuTrigger>
  <ActionButton>
      Edit
  </ActionButton>
  <Menu items={[{name: 'Rollback Options', children: [{name: 'Undo'}, {name: 'Redo'}]}, {name: 'Selected Text Options', children: [{name: 'Cut'}, {name: 'Copy'}, {name: 'Paste'}]}]} itemKey="name">
    {item => (
      <Section items={item.children} aria-label={item.name}>
        {item => <Item>{item.name}</Item>}
      </Section>
    )}
  </Menu>
</MenuTrigger>

Events#


Menu supports selection via mouse, keyboard, and touch.

onOpenChange#

MenuTrigger accepts an onOpenChange handler which is triggered whenever the Menu is opened or closed.

The example below uses onOpenChange to update a separate span element with the current open state of the Menu.

function Example() {
  let [state, setState] = React.useState(false);

  return (
    <div>
      <MenuTrigger onOpenChange={(isOpen) => setState(isOpen)}>
        <ActionButton>
            Edit
        </ActionButton>
        <Menu>
          <Item uniqueKey="cut">Cut</Item>
          <Item uniqueKey="copy">Copy</Item>
          <Item uniqueKey="paste">Paste</Item>
        </Menu>
      </MenuTrigger>
      <span style={{'margin-left': '8px'}}>Current open state: {state.toString()}</span>
    </div>
  );
}

onAction#

Menu accepts an onAction handler which is triggered whenever a Menu Item is selected.

The example below uses the onAction to update text beside the MenuTrigger with the last selected Item.

function Example() {
  let [state, setState] = React.useState(false);

  return (
    <div>
      <MenuTrigger>
        <ActionButton>
            Edit
        </ActionButton>
        <Menu onAction={(value) => setState(value)}>
          <Item uniqueKey="cut">Cut</Item>
          <Item uniqueKey="copy">Copy</Item>
          <Item uniqueKey="paste">Paste</Item>
        </Menu>
      </MenuTrigger>
      <span style={{'margin-left': '8px'}}>onAction: {state.toString()}</span>
    </div>
  );
}

Props#


NameTypeDefaultDescription
childrenReactElement[]The contents of the MenuTrigger, a trigger and a Menu. See the MenuTrigger Content section for more information on what to provide as children.
alignAlignmentWhere the Menu aligns with its trigger.
direction'bottom''top'Where the Menu opens relative to its trigger.
closeOnSelectbooleanWhether the Menu closes when a selection is made.
isOpenbooleanWhether the Menu loads open (controlled).
defaultOpenbooleanWhether the Menu loads open (uncontrolled).
shouldFlipbooleanWhether the element should flip its orientation when there is insufficient space for it to render within the view.
Events
NameTypeDefaultDescription
onOpenChange(isOpen: boolean) => voidHandler that is called when the Menu opens or closes.
NameTypeDefaultDescription
autoFocusbooleanFocusStrategyWhere the focus should be set.
shouldFocusWrapbooleanWhether keyboard navigation is circular.
childrenReactElement<SectionProps<T>>ReactElement<ItemProps<T>>ReactElement<SectionProps<T>>ReactElement<ItemProps<T>>[](item: T) => ReactElement<SectionProps<T>>ReactElement<ItemProps<T>>The contents of the collection.
disabledKeysIterable<Key>They item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with.
itemsIterable<T>Item objects in the collection or section.
itemKeystringProperty name on each item object to use as the unique key. id or key by default.
isLoadingbooleanWhether the items are currently loading.
selectionModeSelectionModeThe type of selection that is allowed in the collection.
disallowEmptySelectionbooleanWhether the collection allows empty selection.
selectedKeys'all'Iterable<Key>The currently selected keys in the collection (controlled).
defaultSelectedKeys'all'Iterable<Key>The initial selected keys in the collection (uncontrolled).
UNSAFE_classNamestring
UNSAFE_styleCSSProperties
Events
NameTypeDefaultDescription
onAction(key: Key) => voidHandler that is called when an item is selected.
onLoadMore() => anyHandler that is called when more items should be loaded, e.g. while scrolling near the bottom.
onSelectionChange(keys: Selection) => anyHandler that is called when the selection changes.
Layout
NameTypeDefaultDescription
flexstringnumberboolean
flexGrownumber
flexShrinknumber
flexBasisnumberstring
alignSelf'auto' | 'normal' | 'start' | 'end' | 'flex-start' | 'flex-end' | 'self-start' | 'self-end' | 'center' | 'stretch'
justifySelf'auto' | 'normal' | 'start' | 'end' | 'flex-start' | 'flex-end' | 'self-start' | 'self-end' | 'center' | 'left' | 'right' | 'stretch'
flexOrdernumber
gridAreastring
gridColumnstring
gridRowstring
gridColumnStartstring
gridColumnEndstring
gridRowStartstring
gridRowEndstring
Spacing
NameTypeDefaultDescription
marginDimensionValue
marginTopDimensionValue
marginLeftDimensionValue
marginRightDimensionValue
marginBottomDimensionValue
marginStartDimensionValue
marginEndDimensionValue
marginXDimensionValue
marginYDimensionValue
Sizing
NameTypeDefaultDescription
widthDimensionValue
minWidthDimensionValue
maxWidthDimensionValue
heightDimensionValue
minHeightDimensionValue
maxHeightDimensionValue
Positioning
NameTypeDefaultDescription
position'static' | 'relative' | 'absolute' | 'fixed' | 'sticky'
topDimensionValue
bottomDimensionValue
leftDimensionValue
rightDimensionValue
startDimensionValue
endDimensionValue
zIndexnumber
isHiddenboolean
Accessibility
NameTypeDefaultDescription
rolestring
idstring
tabIndexnumber
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-controlsstringIdentifies the element (or elements) whose contents or presence are controlled by the current element.
aria-ownsstringIdentifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship between DOM elements where the DOM hierarchy cannot be used to represent the relationship.
aria-hiddenboolean'false''true'Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

Behavioral Options#


Align (MenuTrigger)#

View guidelines

<MenuTrigger align="start">
  <ActionButton>
    placement align=start
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger align="end">
  <ActionButton>
    placement align=end
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

Direction (MenuTrigger)#

View guidelines

<MenuTrigger direction="bottom" shouldFlip={false}>
  <ActionButton>
    placement direction=bottom
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger direction="top" shouldFlip={false}>
  <ActionButton>
    placement direction=top
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

Autofocus (Menu)#

Applying autoFocus to the Menu of the MenuTrigger sets focus to a Menu Item within the Menu upon opening.

This example demonstrates how to use autoFocus to automatically focus the selected Menu Item when the Menu is opened.

<MenuTrigger>
  <ActionButton>
    autoFocus
  </ActionButton>
  <Menu
    selectionMode="single"
    selectedKeys={['copy']}
    autoFocus>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

These examples demonstrate how to use autoFocus to set whether or not the first Menu Item or last Menu Item is focused when the Menu is opened.

<MenuTrigger>
  <ActionButton>
      autofocus=first
  </ActionButton>
  <Menu autoFocus="first">
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger>
  <ActionButton>
    autofocus=last
  </ActionButton>
  <Menu autoFocus="last">
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

Closes on Selection (MenuTrigger)#

The closeOnSelect MenuTrigger prop closes the Menu when an MenuItem is selected (default). Setting the closeOnSelect prop to false would be useful for a Menu listing filtering options where the user would make multiple selections at once.

<MenuTrigger closeOnSelect>
  <ActionButton>
    closeOnSelect=true
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger closeOnSelect={false}>
  <ActionButton>
    closeOnSelect=false
  </ActionButton>
  <Menu selectionMode="multiple">
    <Item uniqueKey="jpg">jpg</Item>
    <Item uniqueKey="png">png</Item>
    <Item uniqueKey="tiff">tiff</Item>
  </Menu>
</MenuTrigger>

Disabled Menu Items (Menu)#

<MenuTrigger>
  <ActionButton>
    Filter
  </ActionButton>
  <Menu
    items={[
      {name: 'tiff', dataId: 'a1b2c3'},
      {name: 'png', dataId: 'g5h1j9'},
      {name: 'jpg', dataId: 'p8k3i4'},
      {name: 'PDF', dataId: 'j7i3a0'}
    ]}
    itemKey="dataId"
    disabledKeys={['a1b2c3', 'p8k3i4']}>
    {item => <Item>{item.name}</Item>}
  </Menu>
</MenuTrigger>

Flipping (MenuTrigger)#

Applying shouldFlip to the MenuTrigger makes the Menu attempt to flip on its main axis in situations where the original placement would cause it to render out of view.

<MenuTrigger shouldFlip>
  <ActionButton>
    shouldFlip=true
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>
<MenuTrigger shouldFlip={false}>
  <ActionButton>
    shouldFlip=false
  </ActionButton>
  <Menu>
    <Item uniqueKey="cut">Cut</Item>
    <Item uniqueKey="copy">Copy</Item>
    <Item uniqueKey="paste">Paste</Item>
  </Menu>
</MenuTrigger>

Open (MenuTrigger)#

The isOpen and defaultOpen props control whether the MenuTrigger is open by default. They apply controlled and uncontrolled behavior on the MenuTrigger respectively.