react-spectrum
react-spectrum copied to clipboard
(Uncontrolled) Menu defaultSelectedKeys does not handle state internally
Provide a general summary of the issue here
When using the Menu component and setting defaultSelectedKeys, the specified key(s) are selected, but further interaction changes nothing.
๐ค Expected Behavior?
Just like other UI, using default... props should set the initial state(s) and handle interaction states.
๐ฏ Current Behavior
https://stackblitz.com/edit/vitejs-vite-lpzaptkr?file=src%2FApp.tsx In the link above, I've created a simple "Text Align" menu:
<MenuTrigger>
<Button>Text align</Button>
<Popover>
<Menu selectionMode="single" defaultSelectedKeys={['center']}>
<MenuItem id="left">Left</MenuItem>
<MenuItem id="center">Center</MenuItem>
<MenuItem id="right">Right</MenuItem>
</Menu>
</Popover>
</MenuTrigger>
I also tested react-aria-components as far back as 1.3.0 and had the same experience.
๐ Possible Solution
When using defaultSelectedKeys, the component should know to handle state internally.
๐ฆ Context
No response
๐ฅ๏ธ Steps to Reproduce
- On initial load, press the trigger to open the menu
- Inspect the "center" item, and notice
aria-checked="true" data-selected="true" - Select either of the other items, which should select that item and close the menu.
- Press the trigger again.
- Inspect the items, and notice that only "center" is selected.
Version
react-aria-components 1.3.0-1.7.1
What browsers are you seeing the problem on?
Chrome
If other, please specify.
Also tested on Firefox and Safari
What operating system are you using?
MacOS Sequoia 15.3.1
๐งข Your Company/Team
No response
๐ท Tracking Issue
No response
The team talked about this today, and we'll actually probably want to go with removing defaultSelectedKeys entirely here for Menus due to the complexities around what would need to happen to have it work like Picker/Combobox/etc. Other than moving that state up into MenuTrigger we would need to handle the individual selection states for submenus/sections etc which gets into some pretty hairy territory. I'd suggest that you use selectedKeys instead and control your selection for this use case for now