Skip to content

Commit

Permalink
[useAutocomplete] Pass only valid values for the getOptionLabel prop (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
rangoo94 authored Feb 14, 2023
1 parent ad09a4f commit 7e6b64d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
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', () => {
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

0 comments on commit 7e6b64d

Please sign in to comment.