import {Layout} from '../../src/Layout'; export default Layout; import docs from 'docs:react-aria-components'; import '../../tailwind/tailwind.css'; import Anatomy from './MenuAnatomy.svg'; import {InlineAlert, Heading, Content} from '@react-spectrum/s2' export const tags = ['dropdown']; export const relatedPages = [ {title: 'useMenu', url: './Menu/useMenu'}, {title: 'Testing Menu', url: './Menu/testing'} ]; export const description = 'Displays a list of actions or options that a user can choose.'; # Menu {docs.exports.Menu.description} ```tsx render type="vanilla" files={["starters/docs/src/Menu.tsx", "starters/docs/src/Menu.css"]} "use client"; import {MenuTrigger, SubmenuTrigger, Menu, MenuItem, MenuSection, Separator, Text, Keyboard} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {Ellipsis, FolderOpen, Pencil, Copy, Trash, Share, Mail, Smartphone, Instagram} from 'lucide-react'; alert('open')} textValue="Open"> Open ⌘O alert('rename')} textValue="Rename"> Rename… ⌘R alert('duplicate')} textValue="Duplicate"> Duplicate ⌘D alert('delete')} textValue="Delete"> Delete… ⌘⌫ Share Email SMS Instagram Show files Show folders ``` ```tsx render type="tailwind" files={["starters/tailwind/src/Menu.tsx"]} "use client"; import {MenuTrigger, SubmenuTrigger, Menu, MenuItem, MenuSection, MenuSeparator} from 'tailwind-starter/Menu'; import {Button} from 'tailwind-starter/Button'; import {MoreHorizontal} from 'lucide-react'; alert('open')}>Open alert('rename')}>Rename… alert('duplicate')}>Duplicate alert('delete')}>Delete… Share Email SMS Instagram Show files Show folders ``` ## Content `Menu` follows the [Collection Components API](collections?component=Menu), accepting both static and dynamic collections. This example shows a dynamic collection, passing a list of objects to the `items` prop, and a function to render the children. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; function Example() { let items = [ { id: 1, name: 'New file…' }, { id: 2, name: 'New window' }, { id: 3, name: 'Open…' }, { id: 4, name: 'Save' }, { id: 5, name: 'Save as…' }, { id: 6, name: 'Revert file' }, { id: 7, name: 'Print…' }, { id: 8, name: 'Close window' }, { id: 9, name: 'Quit' } ]; return ( File {/*- begin highlight -*/} {(item) => {item.name}} {/*- end highlight -*/} ); } ``` ### Text slots Use the `"label"` and `"description"` slots to separate primary and secondary content within a ``. This improves screen reader announcements and can also be used for styling purposes. Use the `` component to display a keyboard shortcut. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem, Text, Keyboard} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Permissions {/*- begin highlight -*/} Copy Copy the selected text {/*- end highlight -*/} ⌘C Cut Cut the selected text ⌘X Paste Paste the copied text ⌘V ``` Accessibility Interactive elements (e.g. buttons) within menu items are not allowed. This will break keyboard and screen reader navigation. Only add textual or decorative graphics (e.g. icons or images) as children. ### Sections Use the `` component to group options. A `` element may also be included to label the section. Sections without a header must have an `aria-label`. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem, MenuSection, Header} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Publish {/*- begin highlight -*/} Export {/*- end highlight -*/} Image… Video… Text… Share YouTube… Instagram… Email… ``` ### Submenus Wrap a `` with a `` to create a submenu. ```tsx render hideImports "use client"; import {MenuTrigger, SubmenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Actions Cut Copy Delete {/*- begin highlight -*/} Share {/*- end highlight -*/} SMS Instagram Email Work Personal ``` ### Separators Separators may be added between menu items or sections in order to create non-labeled groupings. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem, Separator} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Actions New… Open… {/*- begin highlight -*/} {/*- end highlight -*/} Save Save as… Rename… Page setup… Print… ``` ### Asynchronous loading Use [renderEmptyState](#empty-state) to display a loading indicator during initial load. To enable infinite scrolling, render a `` at the end of the menu. Use whatever data fetching library you prefer — this example uses `useAsyncList` from `react-stately`. ```tsx render "use client"; import {MenuTrigger, Menu, MenuItem, MenuLoadMoreItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {Collection} from 'react-aria-components/Collection'; import {useAsyncList} from 'react-aria-components/useAsyncList'; interface Character { name: string; birth_year: string; } function AsyncMenuExample() { let list = useAsyncList({ async load({signal, cursor}) { if (cursor) cursor = cursor.replace(/^http:\/\//i, 'https://'); let res = await fetch(cursor || 'https://swapi.py4e.com/api/people/', {signal}); let json = await res.json(); return {items: json.results, cursor: json.next}; } }); return ( Select Character list.loadingState === 'loading' ? 'Loading…' : 'No characters found'}> {(item) => {item.name}} {/*- begin highlight -*/} {/*- end highlight -*/} ); } ``` ### Links Use the `href` prop on a `` to create a link. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Links {/*- begin highlight -*/} Adobe {/*- end highlight -*/} Apple Google Microsoft ``` By default, links are rendered as an `` element. Use the `render` prop to integrate your framework's link component. An `href` should still be passed to `MenuItem` so React Aria knows it is a link. ```tsx 'href' in domProps ? : } /> ``` ### Empty state ```tsx render hideImports "use client"; import {MenuTrigger, Menu} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; Actions 'No actions available.'}> {[]} ``` ### Autocomplete Popovers can include additional components as siblings of a menu. This example uses an [Autocomplete](Autocomplete) with a [SearchField](SearchField) to let the user filter the items. ```tsx render "use client"; import {Autocomplete, useFilter} from 'react-aria-components/Autocomplete'; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {SearchField} from 'vanilla-starter/SearchField'; function Example() { let {contains} = useFilter({sensitivity: 'base'}); return ( Add tag... {/*- begin highlight -*/} {/*- end highlight -*/} News Travel Shopping Business Entertainment Food Technology Health Science ); } ``` ## Selection Use the `selectionMode` prop to enable single or multiple selection. The selected items can be controlled via the `selectedKeys` prop, matching the `id` prop of the items. Items can be disabled with the `isDisabled` prop. See the [selection guide](selection?component=Menu) for more details. ```tsx render docs={docs.exports.Menu} links={docs.links} props={['selectionMode', 'disallowEmptySelection']} initialProps={{selectionMode: 'multiple'}} wide align="start" "use client"; import type {Selection} from 'react-aria-components/Menu'; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {useState} from 'react'; function Example(props) { let [selected, setSelected] = useState(new Set(['rulers'])); return ( <> View {/*- end highlight -*/} Pixel grid Rulers Comments Layout guides Toolbar Current selection: {selected === 'all' ? 'all' : [...selected].join(', ')} > ); } ``` ### Section-level selection Each section in a menu may have independent selection states by passing `selectionMode` and `selectedKeys` to the `MenuSection`. ```tsx render hideImports "use client"; import type {Selection} from 'react-aria-components/Menu'; import {MenuTrigger, Menu, MenuItem, MenuSection, Header} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {useState} from 'react'; function Example() { let [style, setStyle] = useState(new Set(['bold'])); let [align, setAlign] = useState(new Set(['left'])); return ( Edit Clipboard Cut Copy Paste {/*- begin highlight -*/} {/*- end highlight -*/} Text style Bold Italic Underline Text alignment Left Center Right ); } ``` ## Menu trigger ### Custom trigger `MenuTrigger` works with any pressable React Aria component (e.g. [Button](Button), [Link](Link), etc.). Use the `` component or [usePress](usePress) hook to wrap a custom trigger element such as a third party component or DOM element. ```tsx render hideImports "use client"; import {Pressable} from 'react-aria-components/Menu'; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; {/*- begin highlight -*/} Custom trigger {/*- end highlight -*/} Open Rename… Duplicate Delete… ``` Accessibility Any `` child must have an [interactive ARIA role](https://www.w3.org/TR/wai-aria-1.2/#widget_roles) or use an appropriate semantic HTML element so that screen readers can announce the trigger. Trigger components must forward their `ref` and spread all props to a DOM element. ```tsx const CustomTrigger = React.forwardRef((props, ref) => ( )); ``` ### Long press Use `trigger="longPress"` to open the menu on long press instead of on click/tap. Keyboard users can open the menu using Alt ▼. This is useful when the menu trigger has a primary action on press, and the menu provides secondary actions. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem} from 'vanilla-starter/Menu'; import {Button} from 'vanilla-starter/Button'; import {ChevronDown} from 'lucide-react'; alert('crop')}> Crop Rotate Slice Clone stamp ``` ### Context menu Use `trigger="contextMenu"` to open the menu when right clicking with a mouse, long pressing on touch, or via OS and screen reader specific keyboard shortcuts. The menu is positioned at the point the user clicked. ```tsx render hideImports "use client"; import {MenuTrigger, Menu, MenuItem, SubmenuTrigger, Separator} from 'vanilla-starter/Menu'; import {Button} from 'react-aria-components/Button'; Right click here Open Open with Preview Photoshop Safari Get Info Rename Duplicate Move to Trash ``` ```css render hidden .context-menu-trigger { width: 250px; height: 150px; display: flex; align-items: center; justify-content: center; border: 2px dashed var(--gray-400); border-radius: 10px; background: transparent; font: inherit; color: inherit; outline: none; &[data-focus-visible] { outline: 2px solid var(--focus-ring-color); outline-offset: -2px; } } ``` ## Examples ## API ```tsx links={{MenuTrigger: '#menutrigger', Button: 'Button', Popover: 'Popover', Menu: '#menu', MenuItem: '#menuitem', Separator: 'Separator', MenuSection: '#menusection', SubmenuTrigger: '#submenutrigger', SelectionIndicator: 'selection#animated-selectionindicator', MenuLoadMoreItem: '#menuloadmoreitem'}} ``` ### MenuTrigger ### Menu ### MenuItem ### MenuSection ### SubmenuTrigger ### MenuLoadMoreItem
Current selection: {selected === 'all' ? 'all' : [...selected].join(', ')}