Menu
Menus display a list of actions or options that a user can choose.
| install | yarn add @adobe/react-spectrum |
|---|---|
| added | 3.0.0 |
| usage | import {Menu, MenuTrigger, ContextualHelpTrigger} from '@adobe/react-spectrum' |
Example#
<MenuTrigger>
<ActionButton>
Edit
</ActionButton>
<Menu onAction={(key) => alert(key)}>
<Item key="cut">Cut</Item>
<Item key="copy">Copy</Item>
<Item key="paste">Paste</Item>
<Item key="replace">Replace</Item>
</Menu>
</MenuTrigger>
<MenuTrigger>
<ActionButton>
Edit
</ActionButton>
<Menu onAction={(key) => alert(key)}>
<Item key="cut">Cut</Item>
<Item key="copy">Copy</Item>
<Item key="paste">Paste</Item>
<Item key="replace">Replace</Item>
</Menu>
</MenuTrigger>
<MenuTrigger>
<ActionButton>
Edit
</ActionButton>
<Menu
onAction={(key) =>
alert(key)}
>
<Item key="cut">
Cut
</Item>
<Item key="copy">
Copy
</Item>
<Item key="paste">
Paste
</Item>
<Item key="replace">
Replace
</Item>
</Menu>
</MenuTrigger>
Content#
Menu follows the Collection Components API, accepting both static and dynamic collections. Similar to Picker, Menu accepts <Item> elements as children, each with a key prop. Basic usage of Menu, seen in the example above, shows multiple items populated with a string. Static collections, as in this example, can be used when the full list of items is known ahead of time.
Dynamic collections, as shown below, can be used when the items come from an external data source such as an API call, or update over time. Providing the data in this way allows for Menu to automatically cache the rendering of each item, which dramatically improves performance.
As seen below, an iterable list of items is passed to the Menu using the items prop. Each item accepts a key prop, which is passed to the event handler to identify the selected item. Alternatively, if the item objects contain an id property, this is then used automatically and a key prop is not required. See the Events section for more detail on selection and actions.
function Example() {
let menuItems = [
{name: 'Cut'},
{name: 'Copy'},
{name: 'Paste'},
{name: 'Replace'}
];
return (
<MenuTrigger>
<ActionButton>
Edit
</ActionButton>
<Menu items={menuItems}>
{item => <Item key={item.name}>{item.name}</Item>}
</Menu>
</