Skip to content
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

[useAutocomplete] Pass only valid values for the getOptionLabel prop #36088

Original file line number Diff line number Diff line change
Expand Up @@ -465,14 +465,20 @@ export default function useAutocomplete(props) {
);

const checkHighlightedOptionExists = () => {
const isSameValue = (value1, value2) => {
const label1 = value1 ? getOptionLabel(value1) : '';
const label2 = value2 ? getOptionLabel(value2) : '';
return label1 === label2;
};

if (
highlightedIndexRef.current !== -1 &&
previousProps.filteredOptions &&
previousProps.filteredOptions.length !== filteredOptions.length &&
(multiple
? value.length === previousProps.value.length &&
previousProps.value.every((val, i) => getOptionLabel(value[i]) === getOptionLabel(val))
: getOptionLabel(previousProps.value ?? '') === getOptionLabel(value ?? ''))
: isSameValue(previousProps.value, value))
) {
const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];

Expand Down
19 changes: 19 additions & 0 deletions packages/mui-joy/src/Autocomplete/Autocomplete.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1975,6 +1975,25 @@ describe('Joy <Autocomplete />', () => {
});
expect(textbox).to.have.property('value', 'a');
});

it('should not throw error when nested options are provided', () => {
const { getByRole } = render(
<Autocomplete
openOnFocus
autoHighlight
options={[
{ property: { name: 'one' } },
{ property: { name: 'two' } },
{ property: { name: 'three' } },
]}
getOptionLabel={(option) => option.property.name}
/>,
);

expect(() => {
fireEvent.focus(getByRole('combobox'));
}).not.to.throw();
});
});

describe('prop: onHighlightChange', () => {
Expand Down
20 changes: 20 additions & 0 deletions packages/mui-material/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2418,6 +2418,26 @@ describe('<Autocomplete />', () => {
});
expect(textbox).to.have.property('value', 'a');
});

it('should not throw error when nested options are provided', () => {
ZeeshanTamboli marked this conversation as resolved.
Show resolved Hide resolved
const { getByRole } = render(
<Autocomplete
openOnFocus
autoHighlight
options={[
{ property: { name: 'one' } },
{ property: { name: 'two' } },
{ property: { name: 'three' } },
]}
getOptionLabel={(option) => option.property.name}
renderInput={(params) => <TextField {...params} />}
/>,
);

expect(() => {
fireEvent.focus(getByRole('combobox'));
}).not.to.throw();
});
});

describe('prop: fullWidth', () => {
Expand Down