Skip to content

Controlled react-aria-components Select cannot be nulled #8032

Closed
@pzaczkiewicz-athenahealth

Description

Provide a general summary of the issue here

When supplying a null selectedKey to Select, the HiddenSelect retains its last selected key. This can occur if a value was previously selected, then cleared out via selectedKey getting set to null. This causes the form to be submitted with the previously selected value, even if the field is required. Root cause appears to be value: state.selectedKey ?? undefined,, as it's not distinguishing between null and undefined.

🤔 Expected Behavior?

Form does not submit, as it has a null, required field

😯 Current Behavior

Form submits with previously selected value instead of the currently-displayed null value.

💁 Possible Solution

In useHiddenSelect, use state.selectedKey ?? '' instead

🔦 Context

We've provided a button to clear out form values via controlled state. If this feature is used, inaccurate data could potentially be submitted.

🖥️ Steps to Reproduce

import {
  Button,
  FieldError,
  Form,
  Key,
  Label,
  ListBox,
  ListBoxItem,
  Popover,
  Select,
  SelectValue
} from 'react-aria-components';

export const WithAriaSelect = (): ReactElement => {
  const [selectedKey, setSelectedKey] = useState<Key | null>(null);
  return (
    <Form>
      <Button onPressEnd={() => setSelectedKey(null)}>Reset state</Button>
      <Select isRequired selectedKey={selectedKey} onSelectionChange={setSelectedKey}>
        <Label>Favorite Animal</Label>
        <Button>
          <SelectValue />
          <span aria-hidden="true"></span>
        </Button>
        <Popover>
          <ListBox>
            <ListBoxItem>Aardvark</ListBoxItem>
            <ListBoxItem>Cat</ListBoxItem>
            <ListBoxItem>Dog</ListBoxItem>
            <ListBoxItem>Kangaroo</ListBoxItem>
            <ListBoxItem>Panda</ListBoxItem>
            <ListBoxItem>Snake</ListBoxItem>
          </ListBox>
        </Popover>
        <FieldError />
      </Select>
      <Button type="submit">Submit</Button>
    </Form>
  );
};

Select a value, click the "Reset state" button, Submit

Version

[email protected]

What browsers are you seeing the problem on?

Chrome

If other, please specify.

No response

What operating system are you using?

Windows

🧢 Your Company/Team

Athenahealth/Forge

🕷 Tracking Issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions