New contact
Menus display a list of choices on a temporary surface. Use a menu to show a temporary set of actions, opened from a button or another control. To show actions on screen at all times, use a toolbar instead.
A menu is composed of these parts:
| Part | Use |
|---|---|
MenuTrigger | Holds the element that opens the menu, and the menu's popover |
MenuPopover | The panel of the menu, placed by its trigger |
Menu | The list of items in the panel |
MenuItem | A row of the menu: an action, a choice or a link |
MenuSection, Header | A group of items, and its name |
Separator | A divider between items or sections |
SubmenuTrigger | Holds an item and the popover of the submenu it opens |
Text, Keyboard | The label, the supporting text and the keyboard command of a row |
Import MenuPopover, Menu and MenuItem from @material-web/react, and MenuTrigger, SubmenuTrigger, MenuSection, Header, Separator, Text and Keyboard from react-aria-components, as for React Aria's Menu.
import { Menu, MenuItem, MenuPopover } from '@material-web/react'
import {
Header,
Keyboard,
MenuSection,
MenuTrigger,
Separator,
SubmenuTrigger,
Text,
} from 'react-aria-components'Basic menu
Wrap the element that opens the menu and a MenuPopover in a MenuTrigger. Put a Menu in the popover, and write each row as a MenuItem. Selecting an item closes the menu.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger, Separator } from 'react-aria-components'
export default function Basic() {
return (
<MenuTrigger>
<IconButton aria-label="More options">
<Icon name="more_vert" />
</IconButton>
<MenuPopover>
<Menu>
<MenuItem textValue="Preview">
<Icon slot="leading" name="visibility" />
Preview
</MenuItem>
<MenuItem textValue="Share">
<Icon slot="leading" name="person_add" />
Share
</MenuItem>
<MenuItem textValue="Get link">
<Icon slot="leading" name="link" />
Get link
</MenuItem>
<Separator />
<MenuItem textValue="Remove">
<Icon slot="leading" name="delete" />
Remove
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Write the parts of a menu in this order:
- In the
MenuTrigger, put the element that opens the menu first: anIconButton, aButtonor any other React Aria button. - After it, put the
MenuPopover. - In the
MenuPopover, put theMenu. - In the
Menu, put aMenuItemfor each row.
To open the menu from an element of your own, wrap the element in React Aria's Pressable, and give it an interactive role, such as role="button". See Custom trigger.
To render the items from data, pass items to the Menu and a function as its children. See Collections.
Typing a letter moves the focus to an item by its textValue. An item whose children are a plain string, as in <MenuItem>Preview</MenuItem>, uses that string. Set a textValue on an item that holds anything else, such as an icon or a Keyboard: its types require one.
A menu is 112dp to 280dp wide. A label that is wider wraps onto more lines.
Slots
- leading
- label
- description
- trailing
| Slot | Child | Use |
|---|---|---|
leading | An Icon, a Text or an element of your own, such as an image or a color swatch | Before the label |
label | A Text | The label, which names the item |
description | A Text | The supporting text, under the label. Together with a keyboard command, it describes the item. |
trailing | An Icon, a Text badge, a Keyboard or an element of your own | The item's end, in the order written. Several trailing parts follow each other. |
Write an item's parts as its children, and place each one with a slot. An Icon or a Keyboard may also have no slot. A Keyboard with no slot, the keyboard command, is placed at the item's end, in the order written.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { Keyboard, MenuTrigger, Text } from 'react-aria-components'
export default function Items() {
return (
<MenuTrigger>
<IconButton aria-label="Edit">
<Icon name="edit" />
</IconButton>
<MenuPopover>
<Menu>
<MenuItem textValue="Cut">
<Icon slot="leading" name="content_cut" />
<Text slot="label">Cut</Text>
<Keyboard>⌘X</Keyboard>
</MenuItem>
<MenuItem textValue="Copy">
<Icon slot="leading" name="content_copy" />
<Text slot="label">Copy</Text>
<Text slot="description">Copies the selection</Text>
<Keyboard>⌘C</Keyboard>
</MenuItem>
<MenuItem textValue="Paste">
<Icon slot="leading" name="content_paste" />
<Text slot="label">Paste</Text>
<Text slot="trailing">New</Text>
</MenuItem>
<MenuItem textValue="Save to cloud">
<Icon slot="leading" name="cloud" />
<Text slot="label">Save to cloud</Text>
<Icon slot="trailing" name="open_in_new" />
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Write an item's label as its text, as in <MenuItem>Preview</MenuItem>. The text names the item, also when an Icon is beside it.
For an item with a description, a keyboard command or other text, put the label in a Text with slot="label". The label then names the item, even when the item has an aria-label. Without a label slot, all of the item's text names it. Set an aria-label on an item with no label.
<MenuItem textValue="Copy" onAction={copy}>
<Icon slot="leading" name="content_copy" />
<Text slot="label">Copy</Text>
<Text slot="description">Copies the selection</Text>
<Keyboard>⌘C</Keyboard>
</MenuItem>For a text badge, write <Text slot="trailing">New</Text>. A Text, an Icon or a Keyboard with a slot it does not take throws an Invalid slot error. For an element of your own in a slot, see Account menu.
Account menu
The leading and trailing slots of an item take elements of your own too, such as an avatar, an image or a color swatch. Your own element is placed by its slot attribute, which is not checked. It takes the item's text color unless you set another.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger, Separator, Text } from 'react-aria-components'
const accounts = [
['Britta Holt', 'britta@example.com'],
['Jonas Meyer', 'jonas@example.com'],
] as const
export default function Account() {
return (
<MenuTrigger>
<IconButton variant="tonal" aria-label="Account">
<Icon name="account_circle" />
</IconButton>
<MenuPopover placement="bottom end">
<Menu>
{accounts.map(([name, email]) => (
<MenuItem key={email} textValue={name}>
<span
slot="leading"
className="grid size-8 place-items-center rounded-full bg-primary text-label-lg text-on-primary"
>
{name[0]}
</span>
<Text slot="label">{name}</Text>
<Text slot="description">{email}</Text>
</MenuItem>
))}
<Separator />
<MenuItem textValue="Add another account">
<Icon slot="leading" name="person_add" />
Add another account
</MenuItem>
<MenuItem textValue="Sign out">
<Icon slot="leading" name="logout" />
Sign out
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Sections
Group items in a MenuSection, and name the group with a Header inside it. Separate items or sections with a Separator. A header or a divider does not take the focus.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { Header, MenuSection, MenuTrigger, Separator } from 'react-aria-components'
export default function Sections() {
return (
<MenuTrigger>
<Button variant="tonal">Format</Button>
<MenuPopover>
<Menu>
<MenuSection>
<Header>Style</Header>
<MenuItem textValue="Bold">
<Icon slot="leading" name="format_bold" />
Bold
</MenuItem>
<MenuItem textValue="Italic">
<Icon slot="leading" name="format_italic" />
Italic
</MenuItem>
</MenuSection>
<Separator />
<MenuSection>
<Header>Alignment</Header>
<MenuItem textValue="Left">
<Icon slot="leading" name="format_align_left" />
Left
</MenuItem>
<MenuItem textValue="Center">
<Icon slot="leading" name="format_align_center" />
Center
</MenuItem>
</MenuSection>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Submenus
To open a submenu from an item, wrap the item and a second MenuPopover in a SubmenuTrigger: the item first, then the popover with a Menu in it. Submenus nest to any depth. The item shows an arrow at its end, and its submenu opens beside it, at the item's end and aligned to its top (end top).
- A submenu opens after the pointer has rested on its item for 200ms, on a press, and with Space, Enter or the arrow key toward it. Set
delayon theSubmenuTriggerto change the 200ms. - The arrow key back or Escape closes the submenu. Selecting one of its items closes the whole menu.
- A submenu opens on the side of its item that has room.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { Keyboard, MenuTrigger, Separator, SubmenuTrigger, Text } from 'react-aria-components'
export default function Submenu() {
return (
<MenuTrigger>
<IconButton aria-label="More options">
<Icon name="more_vert" />
</IconButton>
<MenuPopover>
<Menu>
<MenuItem textValue="Share">
<Icon slot="leading" name="person_add" />
<Text slot="label">Share</Text>
<Keyboard>⌘S</Keyboard>
</MenuItem>
<SubmenuTrigger>
<MenuItem textValue="Move to">
<Icon slot="leading" name="drive_file_move" />
Move to
</MenuItem>
<MenuPopover>
<Menu>
<MenuItem>Archive</MenuItem>
<MenuItem>Spam</MenuItem>
<SubmenuTrigger>
<MenuItem>Labels</MenuItem>
<MenuPopover>
<Menu>
<MenuItem>Personal</MenuItem>
<MenuItem>Work</MenuItem>
</Menu>
</MenuPopover>
</SubmenuTrigger>
</Menu>
</MenuPopover>
</SubmenuTrigger>
<Separator />
<MenuItem textValue="Remove">
<Icon slot="leading" name="delete" />
Remove
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Handling actions
Handle an item's press with its own onAction, or with the Menu's onAction, which is called with the item's id.
import { Button, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { useState } from 'react'
import { MenuTrigger, type Key } from 'react-aria-components'
export default function Actions() {
const [action, setAction] = useState<Key | null>(null)
return (
<>
<MenuTrigger>
<Button variant="tonal">Edit</Button>
<MenuPopover>
<Menu onAction={setAction}>
<MenuItem id="cut">Cut</MenuItem>
<MenuItem id="copy">Copy</MenuItem>
<MenuItem id="paste">Paste</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
<span className="text-body-md text-on-surface-variant">
{action ? `Last action: ${action}` : 'No action yet'}
</span>
</>
)
}Selection
Set selectionMode on the Menu to single or multiple. Control the selection with selectedKeys and onSelectionChange, or set the initial selection with defaultSelectedKeys. The keys are the items' ids. See React Aria's Selection guide.
A selected item changes its shape and color and shows a checkmark before its text. The checkmark takes the place of the item's leading part, if it has one.
A menu with a selection opens with the focus on its selected item. With several selected, that is the first key of selectedKeys as you pass it, not the first in the items' order.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { useState } from 'react'
import { MenuTrigger, type Key } from 'react-aria-components'
const orders = ['Name', 'Date modified', 'Size']
export default function SingleSelect() {
const [order, setOrder] = useState<Key>('Name')
return (
<MenuTrigger>
<Button variant="outlined">
<Icon name="sort" />
{`Sort by ${String(order).toLowerCase()}`}
</Button>
<MenuPopover>
<Menu
selectionMode="single"
disallowEmptySelection
selectedKeys={[order]}
onSelectionChange={(keys) => {
const [key] = keys === 'all' ? [] : [...keys]
if (key !== undefined) setOrder(key)
}}
>
{orders.map((name) => (
<MenuItem key={name} id={name}>
{name}
</MenuItem>
))}
</Menu>
</MenuPopover>
</MenuTrigger>
)
}A click selects an item and closes a single-select menu, but leaves a multi-select menu open. Space selects and leaves either menu open, and Enter selects and closes it. Set shouldCloseOnSelect on the Menu, a MenuSection or a MenuItem to choose whether a selection closes the menu. Set disallowEmptySelection to keep a click on the selected item from clearing the selection.
Checkbox and radio menu items
The items of a menu with selectionMode="single" are radio items: choosing one clears the others. The items of a menu with selectionMode="multiple" are checkbox items: each one is turned on and off by itself.
A multi-select menu stays open while its items are clicked.
import { Button, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { useState } from 'react'
import { MenuTrigger, type Selection } from 'react-aria-components'
const diets = ['Gluten-free', 'Kosher', 'Nut-free', 'Vegan', 'Vegetarian']
export default function MultiSelect() {
const [chosen, setChosen] = useState<Selection>(new Set(['Nut-free']))
const names = chosen === 'all' ? diets : diets.filter((diet) => chosen.has(diet))
return (
<MenuTrigger>
<Button variant="outlined">{names.length ? names.join(', ') : 'Diet'}</Button>
<MenuPopover>
<Menu selectionMode="multiple" selectedKeys={chosen} onSelectionChange={setChosen}>
{diets.map((diet) => (
<MenuItem key={diet} id={diet}>
{diet}
</MenuItem>
))}
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Set a selectionMode on a MenuSection to select its items separately from the menu's, or not at all. A section takes selectedKeys, onSelectionChange, defaultSelectedKeys and disallowEmptySelection as the Menu does, and a click in it closes the menu as in a menu of its selectionMode. See Section-level selection.
import { Button, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { useState } from 'react'
import { Header, MenuSection, MenuTrigger, Separator, type Selection } from 'react-aria-components'
export default function SectionSelection() {
const [style, setStyle] = useState<Selection>(new Set(['bold']))
const [align, setAlign] = useState<Selection>(new Set(['left']))
return (
<MenuTrigger>
<Button variant="outlined">Format</Button>
<MenuPopover>
<Menu>
<MenuSection selectionMode="multiple" selectedKeys={style} onSelectionChange={setStyle}>
<Header>Style</Header>
<MenuItem id="bold">Bold</MenuItem>
<MenuItem id="italic">Italic</MenuItem>
<MenuItem id="underline">Underline</MenuItem>
</MenuSection>
<Separator />
<MenuSection
selectionMode="single"
disallowEmptySelection
selectedKeys={align}
onSelectionChange={setAlign}
>
<Header>Alignment</Header>
<MenuItem id="left">Left</MenuItem>
<MenuItem id="center">Center</MenuItem>
<MenuItem id="right">Right</MenuItem>
</MenuSection>
<Separator />
<MenuItem id="clear">Clear formatting</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Opening and closing
A press on the trigger opens the menu. Control the open state with isOpen and onOpenChange on the MenuTrigger, or set defaultOpen to start with the menu open.
Selecting an item, Escape or a click outside closes the menu and returns the focus to the trigger. While the menu is open, the rest of the page does not scroll, and a click outside closes the menu without reaching what was clicked.
Set trigger="longPress" to open the menu with a long press, for a trigger that has an action of its own: a short press runs the trigger's onPress. Alt with Enter, Space or an arrow key opens the menu from the keyboard. See Long press. To open the menu with a right click, see Context menu.
Context menu
Set trigger="contextMenu" on the MenuTrigger to open the menu with a right click, a long press on a touch screen, or the system's keyboard shortcut for a context menu, such as Control+Enter on macOS. The menu opens at the pointer. See React Aria's Context menu.
import { Menu, MenuItem, MenuPopover } from '@material-web/react'
import { Button, MenuTrigger, Separator } from 'react-aria-components'
export default function Context() {
return (
<MenuTrigger trigger="contextMenu">
<Button className="focus-ring box-border grid h-32 w-full max-w-80 place-items-center rounded-shape-md border border-dashed border-outline bg-transparent p-space-200 font-plain text-body-md text-on-surface-variant">
Right-click here, or press and hold
</Button>
<MenuPopover>
<Menu>
<MenuItem>Open</MenuItem>
<MenuItem>Rename</MenuItem>
<MenuItem>Duplicate</MenuItem>
<Separator />
<MenuItem>Move to trash</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Disabled
Set isDisabled on an item to disable it. The keyboard skips it, and it ignores clicks. To disable items by their ids, set disabledKeys on the Menu.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
export default function Disabled() {
return (
<MenuTrigger>
<IconButton aria-label="Edit">
<Icon name="edit" />
</IconButton>
<MenuPopover>
<Menu>
<MenuItem textValue="Undo">
<Icon slot="leading" name="undo" className="rtl:icon-mirrored" />
Undo
</MenuItem>
<MenuItem textValue="Redo" isDisabled>
<Icon slot="leading" name="redo" className="rtl:icon-mirrored" />
Redo
</MenuItem>
<MenuItem textValue="Cut">
<Icon slot="leading" name="content_cut" />
Cut
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Color
Set color on the Menu to standard (the default) or vibrant. Standard is the surface-colored style with lower emphasis, and vibrant is the tertiary-colored style with higher emphasis. A vibrant menu is more prominent: use it sparingly.
A submenu's Menu uses the color of the Menu it is in unless you set its own.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
export default function Colors() {
return (
<>
{(['standard', 'vibrant'] as const).map((color) => (
<MenuTrigger key={color}>
<Button variant="tonal" className="capitalize">
{color}
</Button>
<MenuPopover>
<Menu color={color}>
<MenuItem textValue="Preview">
<Icon slot="leading" name="visibility" />
Preview
</MenuItem>
<MenuItem textValue="Share">
<Icon slot="leading" name="person_add" />
Share
</MenuItem>
<MenuItem textValue="Get link">
<Icon slot="leading" name="link" />
Get link
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
))}
</>
)
}Placement
Place the menu with these props of the MenuPopover:
placementis the side of the trigger the menu opens on:bottom start(the default), below the trigger and aligned to its start, or any other of React Aria's placements.offsetis the distance between the menu and the trigger: 0 (the default) keeps them flush.containerPaddingis the distance the menu keeps from the window's edges: 8dp (the default).shouldFlipcontrols whether the menu turns to the side with more room, which it does unless you turn it off.
import { Button, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
const placements = ['bottom start', 'bottom end', 'top start', 'end top', 'start top'] as const
export default function Placement() {
return (
<>
{placements.map((placement) => (
<MenuTrigger key={placement}>
<Button variant="tonal">{placement}</Button>
<MenuPopover placement={placement}>
<Menu>
<MenuItem>Preview</MenuItem>
<MenuItem>Share</MenuItem>
<MenuItem>Get link</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
))}
</>
)
}To make the menu as wide as its trigger, set className="w-(--trigger-width)" on the MenuPopover.
Size and scrolling
When its items do not fit, the menu takes the room there is in the window and scrolls. To make it shorter, set maxHeight on the MenuPopover, in pixels.
import { Button, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
const states = [
'Alabama',
'Alaska',
'Arizona',
'Arkansas',
'California',
'Colorado',
'Connecticut',
'Delaware',
'Florida',
'Georgia',
'Hawaii',
'Idaho',
'Illinois',
'Indiana',
'Iowa',
'Kansas',
'Kentucky',
'Louisiana',
'Maine',
'Maryland',
]
const heights = [
['State', undefined],
['State, max 240dp', 240],
] as const
export default function Scrolling() {
return (
<>
{heights.map(([label, maxHeight]) => (
<MenuTrigger key={label}>
<Button variant="outlined">{label}</Button>
<MenuPopover maxHeight={maxHeight}>
<Menu>
{states.map((state) => (
<MenuItem key={state}>{state}</MenuItem>
))}
</Menu>
</MenuPopover>
</MenuTrigger>
))}
</>
)
}Links
Give an item an href to make it a link. It also takes target and rel. To follow the link with a client-side router, wrap the app in React Aria's RouterProvider. See Routing.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
export default function Links() {
return (
<MenuTrigger>
<Button variant="tonal">Read more</Button>
<MenuPopover>
<Menu>
<MenuItem href="/components/fab-menu">FAB menu</MenuItem>
<MenuItem
textValue="Menus in Material 3"
href="https://m3.material.io/components/menus"
target="_blank"
rel="noreferrer"
>
Menus in Material 3
<Icon slot="trailing" name="open_in_new" />
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Right to left
A menu's direction follows the locale, not the page's dir. For a right-to-left menu, set the locale with I18nProvider. The arrow keys follow the locale too. See Internationalization.
Customization
Pass classes in className to restyle a part of a menu: the MenuPopover is the panel, with its corners, shadow and width, the Menu is the list, with its background color, and a MenuItem is a row. A class of yours replaces the part's own class for the same property. See Styling for the classes, the states and the theme.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger, Separator } from 'react-aria-components'
export default function Custom() {
return (
<MenuTrigger>
<Button variant="tonal">Message</Button>
<MenuPopover>
<Menu className="bg-surface-container-high">
<MenuItem textValue="Star">
{({ isFocused }) => (
<>
<Icon
slot="leading"
name="star"
className={isFocused ? 'icon-filled' : undefined}
/>
Star
</>
)}
</MenuItem>
<MenuItem textValue="Archive">
<Icon slot="leading" name="archive" />
Archive
</MenuItem>
<Separator />
<MenuItem textValue="Delete" className="text-error">
<Icon slot="leading" name="delete" className="text-error" />
Delete
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}In a standard menu, an item's icons, supporting text and keyboard command keep a color of their own: to recolor them with the item, give them the class too.
- States: Style a state of an item with its variant, such as
focus:,selected:ordisabled:. See States. - Functions: Pass a function as an item's children to render them from the item's state:
isHovered,isPressed,isFocused,isFocusVisible,isSelected,isDisabled,hasSubmenuandisOpen. On an item,isFocusedis true for the keyboard or the pointer, andisFocusVisiblefor the keyboard only.classNameandstyletake a function too, on each of the three parts. See Children as a function. - Ancestors: The menu is rendered at the end of the page, not next to its trigger. A density class, a color role or a
data-themeon an element around the trigger does not reach it. Set it on theMenuPopoveritself, or on the root element. - Every menu: To restyle all the menus at once, change the theme.
Density
Add density-1, density-2 or density-3 to the MenuPopover to make each item 4dp shorter for each step. See Density.
import { Button, Icon, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
const densities = [
['Default', undefined],
['Dense', 'density-3'],
] as const
export default function Dense() {
return (
<>
{densities.map(([label, density]) => (
<MenuTrigger key={label}>
<Button variant="tonal">{label}</Button>
<MenuPopover className={density}>
<Menu>
<MenuItem textValue="Single">
<Icon slot="leading" name="density_large" />
Single
</MenuItem>
<MenuItem textValue="1.15">
<Icon slot="leading" name="density_medium" />
1.15
</MenuItem>
<MenuItem textValue="Double">
<Icon slot="leading" name="density_small" />
Double
</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
))}
</>
)
}Note: The menu is rendered at the end of the page, not next to its trigger. A density class on an element around the trigger does not reach it. Add the class to the MenuPopover, or to an element that contains it, such as the document's root element.
Transitions
Set shouldSkipAnimation on the MenuPopover to open and close the menu instantly, as in a dense product on desktop.
import { Icon, IconButton, Menu, MenuItem, MenuPopover } from '@material-web/react'
import { MenuTrigger } from 'react-aria-components'
export default function Instant() {
return (
<MenuTrigger>
<IconButton aria-label="More options">
<Icon name="more_vert" />
</IconButton>
<MenuPopover shouldSkipAnimation>
<Menu>
<MenuItem>Preview</MenuItem>
<MenuItem>Share</MenuItem>
<MenuItem>Get link</MenuItem>
</Menu>
</MenuPopover>
</MenuTrigger>
)
}Limitations
Controls in items
An item takes every press on its row, and Tab does not move the focus into it, so a button, a switch or another control in an item cannot be used. An item performs one action. For items that turn on and off, use checkbox items.
Uncontrolled selection
A selection set with defaultSelectedKeys starts over each time the menu opens. Control it with selectedKeys to keep it.
Use cases
Material lists what people should be able to do with assistive technology:
- Navigate to, open, and close a menu
- Navigate between and select menu items
Interaction and style
- States: Hovering an item shows a state layer, and the pointer focuses it. Keyboard focus shows a focus ring inside the item, and a press with a mouse or touch does not. The trigger keeps its pressed state layer while the menu is open. A selected item changes its shape and color and shows a checkmark, so that color is not its only cue, as Material advises.
- Touch target: An item can be pressed anywhere in its 48dp row, the 2dp above and below it included.
- Color contrast: Every text in a standard or a vibrant menu has 4.5:1 contrast or more with its fill, and its icons and checkmarks 3:1, in light and dark schemes at every contrast level. Keep that contrast when you change its colors.
- Density: A density class on the
MenuPopovermakes each item and its row 4dp shorter for each step, so that the row is less than 48dp tall. See Density. - Motion: With reduced motion, the menu opens and closes at once, and a selected item's checkmark is drawn at once.
- Forced colors: In forced colors, the panel keeps an edge, a selected item is filled with the system's highlight color, and a disabled item takes the system's color for disabled text.
- Right to left: A menu's direction and its arrow keys follow the locale. See Right to left.
- Slots: Material advises that what you put in a slot keep the item's padding and its 48dp target, and that it be no button, switch or other control. An item takes every press on its row, and Tab does not move the focus into it. See Controls in items.
Focus
- Space, Enter or Down arrow on the trigger opens the menu with the first item focused, as Material advises, and Up arrow with the last. A click opens it with the focus on the menu itself, and Down arrow or Up arrow then moves the focus to the first or the last item.
- A menu with a selection opens with the focus on its selected item.
- Tab and Shift+Tab leave the focus on the item it is on, and do not reach the page behind the menu.
- Selecting an item, Escape or a click outside closes the menu and returns the focus to the trigger.
- A
Separatorand aHeadertake no focus, as Material advises for dividers, and the keyboard skips a disabled item.
Keyboard navigation
| Keys | Actions |
|---|---|
| Space or Enter | Open the menu from the trigger with the first item focused, or select the focused item |
| Down arrow | Open the menu from the trigger with the first item focused, or move the focus to the next item |
| Up arrow | Open the menu from the trigger with the last item focused, or move the focus to the previous item |
| Home | Move the focus to the first item |
| End | Move the focus to the last item |
| Page Up | Move the focus up by a page of items |
| Page Down | Move the focus down by a page of items |
| Right arrow | Open the focused item's submenu, with its first item focused |
| Left arrow | Close the submenu, with the focus back on its item |
| Letter keys | Move the focus to the next item that starts with the typed letters |
| Escape | Close the menu, or the open submenu alone |
| Tab or Shift+Tab | Leave the focus where it is |
- Down arrow and Up arrow go round from either end of the menu.
- In a menu with a
selectionMode, Space selects an item and leaves the menu open, and Enter selects it and closes the menu. See Selection. - Space and Enter open the submenu of the focused item too.
- In a right-to-left locale, Right arrow and Left arrow swap.
- Typing finds an item by its
textValue. Set atextValueon an item that holds more than its text. - With
trigger="longPress", Alt with Space, Enter or an arrow key opens the menu. See Opening and closing.
Labeling elements
- The menu has the
menurole, named by its trigger. The trigger reports the menu witharia-haspopup, and whether it is open witharia-expanded. - A trigger with an icon alone, such as an
IconButton, needs anaria-label, which names the menu too. - An item has the
menuitemrole. In a single-select menu it has themenuitemradiorole, and in a multi-select menu themenuitemcheckboxrole, either of which reports whether the item is selected witharia-checked. - The label names the item: its text, or the
Textin itslabelslot. An icon beside a label is decorative, and so is the checkmark, so that the name matches the item's text, as Material advises. Set anaria-labelon an item with no label. - The description and the keyboard command describe the item.
- Name a
MenuSectionwith aHeader. - An item that opens a submenu reports it with
aria-haspopup, and whether the submenu is open witharia-expanded. The item names the submenu. - A disabled item reports it with
aria-disabled. - While the menu is open, the rest of the page is hidden from assistive technology.
MenuPopover
These defaults differ from the ones in the table: placement is bottom start in a MenuTrigger and end top in a SubmenuTrigger, offset is 0 and containerPadding is 8.
Props of MenuPopover (37)
classNameClassNameOrFunction<PopoverRenderProps>Default'react-aria-Popover'The CSS className for the element. A function may be provided to compute the class based on component state.
triggerstringThe name of the component that triggered the popover. This is reflected on the element as the
data-triggerattribute, and can be used to provide specific styles for the popover depending on which element triggered it.triggerRefRefObject<Element | null>The ref for the element which the popover positions itself with respect to.
When used within a trigger component such as DialogTrigger, MenuTrigger, Select, etc., this is set automatically. It is only required when used standalone.
isEnteringbooleanWhether the popover is currently performing an entry animation.
isExitingbooleanWhether the popover is currently performing an exit animation.
shouldSkipAnimationbooleanWhether the popover should appear and disappear without an entry or exit animation. This is used by components such as PreviewTrigger to skip animations when quickly swapping between overlays.
UNSTABLE_portalContainerdeprecatedElementDefaultdocument.bodyThe container element in which the overlay portal will be placed. This may have unknown behavior depending on where it is portalled to.
offsetnumberDefault8The additional offset applied along the main axis between the element and its anchor element.
placement'start' | 'end' | 'bottom' | 'bottom left' | 'bottom right' | 'bottom start' | 'bottom end' | 'top' | 'top left' | 'top right' | 'top start' | 'top end' | 'left' | 'left top' | 'left bottom' | 'start top' | 'start bottom' | 'right' | 'right top' | 'right bottom' | 'end top' | 'end bottom'Default'bottom'The placement of the element with respect to its anchor element.
containerPaddingnumberDefault12The placement padding that should be applied between the element and its surrounding container.
crossOffsetnumberDefault0The additional offset applied along the cross axis between the element and its anchor element.
shouldFlipbooleanDefaulttrueWhether the element should flip its orientation (e.g. top to bottom or left to right) when there is insufficient room for it to render completely.
shouldCloseOnInteractOutside(element: Element) => booleanWhen user interacts with the argument element outside of the popover ref, return true if onClose should be called. This gives you a chance to filter out interaction with elements that should not dismiss the popover. By default, onClose will always be called on interaction outside the popover ref.
isKeyboardDismissDisabledbooleanDefaultfalseWhether pressing the escape key to close the popover should be disabled.
Most popovers should not use this option. When set to true, an alternative way to close the popover with a keyboard must be provided.
boundaryElementElementDefaultdocument.bodyElement that that serves as the positioning boundary.
arrowRefRefObject<Element | null>A ref for the popover arrow element.
scrollRefRefObject<Element | null>DefaultoverlayRefA ref for the scrollable region within the overlay.
shouldUpdatePositionbooleanDefaulttrueWhether the overlay should update its position automatically.
maxHeightnumberThe maxHeight specified for the overlay element. By default, it will take all space up to the current viewport height.
arrowBoundaryOffsetnumberDefault0The minimum distance the arrow's edge should be from the edge of the overlay element.
getTargetRect(target: Element) => DOMRect | null | undefinedDefaulttarget.getBoundingClientRect()Overrides the target element's bounding rectangle. Useful for positioning relative to a specific point such as the mouse cursor (e.g. context menus) or text selection.
onFocusWithin(e: FocusEvent) => voidHandler that is called when the target element or a descendant receives focus.
onBlurWithin(e: FocusEvent) => voidHandler that is called when the target element and all descendants lose focus.
onFocusWithinChange(isFocusWithin: boolean) => voidHandler that is called when the the focus within state changes.
isNonModalbooleanWhether the popover is non-modal, i.e. elements outside the popover may be interacted with by assistive technologies.
Most popovers should not use this option as it may negatively impact the screen reader experience. Only use with components such as combobox, which are designed to handle this situation carefully.
isOpenbooleanWhether the overlay is open by default (controlled).
defaultOpenbooleanWhether the overlay is open by default (uncontrolled).
onOpenChange(isOpen: boolean) => voidHandler that is called when the overlay's open state changes.
childrenChildrenOrFunction<T>The children of the component. A function may be provided to alter the children based on component state.
styleCSSProperties | (values: PopoverRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
renderDOMRenderFunction<'div', PopoverRenderProps>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Requirements:
- You must render the expected element type (e.g. if
<button>is expected, you cannot render an<a>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
slotstring | nullA slot name for the component. Slots allow the component to receive props from a parent component. An explicit
nullvalue indicates that the local props completely override all props received from a parent.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-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
refRef<HTMLElement>
MenuPopover also takes the 70 attributes and events of the element it renders.
Menu
color'standard' | 'vibrant'Default'standard'Menus have two color mappings:
Standard: Surface-based, lower visual emphasis
Vibrant: Tertiary-based, higher visual emphasis
Vibrant menus are more prominent, and should be used sparingly.
Props of Menu (26)
classNameClassNameOrFunction<MenuRenderProps>Default'react-aria-Menu'The CSS className for the element. A function may be provided to compute the class based on component state.
renderEmptyState() => ReactNodeProvides content to display when there are no items in the menu.
shouldCloseOnSelectbooleanWhether the menu should close when the menu item is selected.
idstringThe element's unique identifier. See MDN.
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-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
autoFocus'first' | 'last' | booleanWhere the focus should be set.
selectionMode'none' | 'single' | 'multiple'The type of selection that is allowed in the collection.
itemsIterable<T>Item objects in the collection.
escapeKeyBehavior'none' | 'clearSelection'Default'clearSelection'Whether pressing the escape key should clear selection in the menu or not.
Most experiences should not modify this option as it eliminates a keyboard user's ability to easily clear selection. Only use if the escape key is being handled externally or should not trigger selection clearing contextually.
onAction(key: Key, value: T) => voidHandler that is called when an item is selected.
disabledKeysIterable<Key>The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with.
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).
onSelectionChange(keys: Selection) => voidHandler that is called when the selection changes.
shouldFocusWrapbooleanWhether keyboard navigation is circular.
onClose() => voidHandler that is called when the menu should close after selecting an item.
childrenReactNode | ((item: T) => ReactNode)The contents of the collection.
dependenciesReadonlyArray<any>Values that should invalidate the item cache when using dynamic collections.
styleCSSProperties | (values: MenuRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
renderDOMRenderFunction<'div', MenuRenderProps>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Requirements:
- You must render the expected element type (e.g. if
<button>is expected, you cannot render an<a>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
slotstring | nullA slot name for the component. Slots allow the component to receive props from a parent component. An explicit
nullvalue indicates that the local props completely override all props received from a parent.refRef<HTMLDivElement>
Menu also takes the 70 attributes and events of the element it renders.
MenuItem
Props of MenuItem (32)
classNameClassNameOrFunction<MenuItemRenderProps>Default'react-aria-MenuItem'The CSS className for the element. A function may be provided to compute the class based on component state.
idKeyThe unique id of the item.
valueobjectThe object value that this item represents. When using dynamic collections, this is set automatically.
textValuestringA string representation of the item's contents, used for features like typeahead.
aria-labelstringAn accessibility label for this item.
isDisabledbooleanWhether the item is disabled.
onAction() => voidHandler that is called when the item is selected.
shouldCloseOnSelectbooleanWhether the menu should close when the menu item is selected.
styleCSSProperties | (values: MenuItemRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
childrenChildrenOrFunction<T>The children of the component. A function may be provided to alter the children based on component state.
render(props: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> | DetailedHTMLProps<LinkWithRequiredHref, HTMLAnchorElement>, renderProps: MenuItemRenderProps) => ReactElement<unknown, string | JSXElementConstructor<any>>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Note: You can check if
'href' in propsin order to tell whether to render an<a>element.Requirements:
- You must render the expected element type (e.g. if
<a>is expected, you cannot render a<button>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
hrefHrefA URL to link to. See MDN.
hrefLangstringHints at the human language of the linked URL. SeeMDN.
targetHTMLAttributeAnchorTargetThe target window for the link. See MDN.
relstringThe relationship between the linked resource and the current page. See MDN.
downloadboolean | stringCauses the browser to download the linked URL. A string may be provided to suggest a file name. See MDN.
pingstringA space-separated list of URLs to ping when the link is followed. See MDN.
referrerPolicy'' | 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'How much of the referrer to send when following the link. See MDN.
routerOptionsOptions for the configured client side router.
onHoverStart(e: HoverEvent) => voidHandler that is called when a hover interaction starts.
onHoverEnd(e: HoverEvent) => voidHandler that is called when a hover interaction ends.
onHoverChange(isHovering: boolean) => voidHandler that is called when the hover state changes.
onFocus(e: FocusEvent<Target>) => voidHandler that is called when the element receives focus.
onBlur(e: FocusEvent<Target>) => voidHandler that is called when the element loses focus.
onFocusChange(isFocused: boolean) => voidHandler that is called when the element's focus status changes.
onPress(e: PressEvent) => voidHandler that is called when the press is released over the target.
onPressStart(e: PressEvent) => voidHandler that is called when a press interaction starts.
onPressEnd(e: PressEvent) => voidHandler that is called when a press interaction ends, either over the target or when the pointer leaves the target.
onPressChange(isPressed: boolean) => voidHandler that is called when the press state changes.
onPressUp(e: PressEvent) => voidHandler that is called when a press is released over the target, regardless of whether it started on the target or not.
onClick(e: MouseEvent<FocusableElement>) => voidNot recommended – use
onPressinstead.onClickis an alias foronPressprovided for compatibility with other libraries.onPressprovides additional event details for non-mouse interactions.refRef<HTMLDivElement>
MenuItem also takes the 69 attributes and events of the element it renders.