react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

(Uncontrolled) Menu defaultSelectedKeys does not handle state internally

Open JawsomeJason opened this issue 8 months ago โ€ข 1 comments

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

  1. On initial load, press the trigger to open the menu
  2. Inspect the "center" item, and notice aria-checked="true" data-selected="true"
  3. Select either of the other items, which should select that item and close the menu.
  4. Press the trigger again.
  5. 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

JawsomeJason avatar Apr 06 '25 22:04 JawsomeJason

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

LFDanLu avatar May 28 '25 22:05 LFDanLu