-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
Summary
The Select component from react-aria-components does not set a form value during the initial render.
This means when using new FormData(formRef.current), in a useEffect for example, the defaultSelectedKey passed to Select will not be accessible.
This only happens when client side rendering. If the select is rendered on the server and hydrated on the client the value will be accessible during the initial render as well.
When using setTimeout to delay the reading of the form values by one render cycle the value will be available.
Other form components don't seem to have this issue.
🤔 Expected Behavior?
The defaultSelectedKey is available on the form element during the initial render.
😯 Current Behavior
The defaultSelectedKey is NOT available on the form element during the initial render, but gets updated on the next render cycle.
💁 Possible Solution
Looking into it, the issue seems to be that the collection does not contain the keys during the initial render, causing the HiddenSelect not to render any options.
The state correctly contains the selected key.
Relevant code:
react-spectrum/packages/@react-aria/select/src/HiddenSelect.tsx
Lines 140 to 151 in e677260
| {[...state.collection.getKeys()].map(key => { | |
| let item = state.collection.getItem(key); | |
| if (item && item.type === 'item') { | |
| return ( | |
| <option | |
| key={item.key} | |
| value={item.key}> | |
| {item.textValue} | |
| </option> | |
| ); | |
| } | |
| })} |
If this is not feasible to fix in the collection API itself, another possible solution could be to use a simple hidden input during the initial render, or make sure the selected key is always added as an <option>.
🔦 Context
We are using uncontrolled components in our form, but sometimes still need to get the current form values.
🖥️ Steps to Reproduce
Visit the reproduction and see that the select value is not displayed.
When wrapping the setFormData call in setTimeout it does work.
Version
react-aria-components: 1.10.1
What browsers are you seeing the problem on?
Chrome
What operating system are you using?
MacOS
🕷 Tracking Issue
No response