Skip to content
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
2 changes: 1 addition & 1 deletion packages/react-dom-bindings/src/client/ReactDOMSelect.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function updateOptions(
defaultSelected = options[i];
}
}
if (defaultSelected !== null) {
if (defaultSelected !== null && node.size <= 1) {
defaultSelected.selected = true;
}
}
Expand Down
57 changes: 57 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMSelect-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,63 @@ describe('ReactDOMSelect', () => {
expect(select.selectedIndex).toBe(-1);
});

it('does not select the first option when size > 1 and value does not match', async () => {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);

await act(() => {
root.render(
<select size="2" value="does-not-exist" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
});

const select = container.firstChild;

// On initial render the browser handles list box selection (nothing selected).
// On subsequent renders updateOptions runs; it must not fall back to the
// first option for a list box (size > 1).
await act(() => {
root.render(
<select size="2" value="does-not-exist" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
});

expect(select.options[0].selected).toBe(false);
expect(select.options[1].selected).toBe(false);
expect(select.options[2].selected).toBe(false);
expect(select.selectedIndex).toBe(-1);
});

it('selects the matching option when size > 1 and value matches', async () => {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);

await act(() => {
root.render(
<select size="2" value="giraffe" onChange={noop}>
<option value="monkey">A monkey!</option>
<option value="giraffe">A giraffe!</option>
<option value="gorilla">A gorilla!</option>
</select>,
);
});

const select = container.firstChild;

expect(select.options[0].selected).toBe(false);
expect(select.options[1].selected).toBe(true);
expect(select.options[2].selected).toBe(false);
expect(select.value).toBe('giraffe');
});

it('should remember value when switching to uncontrolled', async () => {
const stub = (
<select value={'giraffe'} onChange={noop}>
Expand Down