Skip to content

fix: Allow selectedKey=null to clear value in HiddenSelect #8330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions packages/@react-aria/select/src/HiddenSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/

import {FocusableElement, RefObject} from '@react-types/shared';
import React, {JSX, ReactNode, useRef} from 'react';
import React, {JSX, ReactNode, useCallback, useRef} from 'react';
import {selectData} from './useSelect';
import {SelectState} from '@react-stately/select';
import {useFormReset} from '@react-aria/utils';
Expand Down Expand Up @@ -75,6 +75,9 @@ export function useHiddenSelect<T>(props: AriaHiddenSelectOptions, state: Select
focus: () => triggerRef.current?.focus()
}, state, props.selectRef);

// eslint-disable-next-line react-hooks/exhaustive-deps
let onChange = useCallback((e: React.ChangeEvent<HTMLSelectElement> | React.FormEvent<HTMLSelectElement>) => state.setSelectedKey(e.currentTarget.value), [state.setSelectedKey]);

// In Safari, the <select> cannot have `display: none` or `hidden` for autofill to work.
// In Firefox, there must be a <label> to identify the <select> whereas other browsers
// seem to identify it just by surrounding text.
Expand All @@ -99,8 +102,9 @@ export function useHiddenSelect<T>(props: AriaHiddenSelectOptions, state: Select
disabled: isDisabled,
required: validationBehavior === 'native' && isRequired,
name,
value: state.selectedKey ?? undefined,
onChange: (e: React.ChangeEvent<HTMLSelectElement>) => state.setSelectedKey(e.target.value)
value: state.selectedKey ?? '',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was changed previously in #7670 to fix a different issue. @snowystinger do you remember what was going on there?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, that was to fix the autocomplete. If I recall correctly, it viewed the '' as a controlled value for the field and wouldn't autofill as a result, React would just overwrite it with the empty string again as there was no onChange event. There is apparently an onInput change for it though, so we can use that to update with the value for auto fill.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, I missed the onInput. Does having both cause setSelectedKey to run twice then?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good question, i doubt any of our tests check that, so will need to verify

onChange,
onInput: onChange
}
};
}
Expand Down
1 change: 1 addition & 0 deletions packages/@react-spectrum/picker/test/Picker.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1715,6 +1715,7 @@ describe('Picker', function () {
expect(options.length).toBe(60);
options.forEach((option, index) => index > 0 && expect(option).toHaveTextContent(states[index - 1].name));

fireEvent.input(hiddenSelect, {target: {value: 'CA'}});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just double checking, is this just testing that onSelectionChange isn't called twice? asking because it seems it was passing before the changes in HIddenSelect

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah

fireEvent.change(hiddenSelect, {target: {value: 'CA'}});
expect(onSelectionChange).toHaveBeenCalledTimes(1);
expect(onSelectionChange).toHaveBeenLastCalledWith('CA');
Expand Down
40 changes: 39 additions & 1 deletion packages/react-aria-components/stories/Select.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* governing permissions and limitations under the License.
*/

import {Button, Collection, Label, ListBox, ListLayout, OverlayArrow, Popover, Select, SelectValue, Virtualizer} from 'react-aria-components';
import {Button, Collection, FieldError, Form, Input, Label, ListBox, ListLayout, OverlayArrow, Popover, Select, SelectValue, TextField, Virtualizer} from 'react-aria-components';
import {LoadingSpinner, MyListBoxItem} from './utils';
import React from 'react';
import styles from '../example/index.css';
Expand Down Expand Up @@ -174,3 +174,41 @@ AsyncVirtualizedCollectionRenderSelect.story = {
delay: 50
}
};

export const SelectSubmitExample = () => (
<Form>
<TextField
isRequired
autoComplete="username"
className={styles.textfieldExample}
name="username">
<Label>Username</Label>
<Input />
<FieldError className={styles.errorMessage} />
</TextField>
<Select isRequired autoComplete="organization" name="company">
<Label style={{display: 'block'}}>Company</Label>
<Button>
<SelectValue />
<span aria-hidden="true" style={{paddingLeft: 5}}>
</span>
</Button>
<Popover>
<OverlayArrow>
<svg height={12} width={12}>
<path d="M0 0,L6 6,L12 0" />
</svg>
</OverlayArrow>
<ListBox className={styles.menu}>
<MyListBoxItem>Adobe</MyListBoxItem>
<MyListBoxItem>Google</MyListBoxItem>
<MyListBoxItem>Microsoft</MyListBoxItem>
</ListBox>
</Popover>
<FieldError className={styles.errorMessage} />
</Select>
<Button type="submit">Submit</Button>
<Button type="reset">Reset</Button>
</Form>
);
42 changes: 41 additions & 1 deletion packages/react-aria-components/test/Select.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/

import {act, pointerMap, render, within} from '@react-spectrum/test-utils-internal';
import {Button, FieldError, Label, ListBox, ListBoxItem, Popover, Select, SelectContext, SelectStateContext, SelectValue, Text} from '../';
import {Button, FieldError, Form, Label, ListBox, ListBoxItem, Popover, Select, SelectContext, SelectStateContext, SelectValue, Text} from '../';
import React from 'react';
import {User} from '@react-aria/test-utils';
import userEvent from '@testing-library/user-event';
Expand Down Expand Up @@ -413,4 +413,44 @@ describe('Select', () => {
let text = popover.querySelector('.react-aria-Text');
expect(text).not.toHaveAttribute('id');
});

it('should not submit if required and selectedKey is null', async () => {
const onSubmit = jest.fn().mockImplementation(e => e.preventDefault());

function Test() {
const [selectedKey, setSelectedKey] = React.useState(null);
return (
<Form onSubmit={onSubmit}>
<TestSelect
isRequired
name="select"
selectedKey={selectedKey}
onSelectionChange={setSelectedKey} />
<Button data-testid="submit" type="submit">
Submit
</Button>
<Button data-testid="clear" onPress={() => setSelectedKey(null)}>
Reset
</Button>
</Form>
);
}

const {getByTestId} = render(<Test />);
const wrapper = getByTestId('select');
const selectTester = testUtilUser.createTester('Select', {root: wrapper});
const trigger = selectTester.trigger;
const submit = getByTestId('submit');

expect(trigger).toHaveTextContent('Select an item');
await selectTester.selectOption({option: 'Cat'});
expect(trigger).toHaveTextContent('Cat');
await user.click(submit);
expect(onSubmit).toHaveBeenCalledTimes(1);
await user.click(getByTestId('clear'));
expect(trigger).toHaveTextContent('Select an item');
await user.click(submit);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(document.querySelector('[name=select]').value).toBe('');
});
});