Skip to content

Commit 130b7c1

Browse files
[autocomplete] Fix ArrowLeft crash when value is not set with single-value rendering (#47214)
Co-authored-by: ZeeshanTamboli <[email protected]>
1 parent c3edec2 commit 130b7c1

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

packages/mui-material/src/Autocomplete/Autocomplete.test.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3683,6 +3683,49 @@ describe('<Autocomplete />', () => {
36833683

36843684
expect(view.container.querySelector(`.${chipClasses.root}`)).to.have.text('0');
36853685
});
3686+
3687+
it('should not throw error on pressing ArrowLeft key with no value in single value rendering', () => {
3688+
render(
3689+
<Autocomplete
3690+
options={['one', 'two', 'three']}
3691+
renderValue={(value, getItemProps) => {
3692+
return value ? <Chip label={value} {...getItemProps()} /> : null;
3693+
}}
3694+
renderInput={(params) => <TextField {...params} autoFocus />}
3695+
/>,
3696+
);
3697+
3698+
const textbox = screen.getByRole('combobox');
3699+
3700+
expect(() => {
3701+
fireEvent.keyDown(textbox, { key: 'ArrowLeft' });
3702+
}).not.to.throw();
3703+
3704+
expect(textbox).toHaveFocus();
3705+
});
3706+
3707+
it('should not throw error on pressing ArrowLeft key with input text but no value in single value rendering', () => {
3708+
render(
3709+
<Autocomplete
3710+
options={['one', 'two', 'three']}
3711+
renderValue={(value, getItemProps) => {
3712+
return value ? <Chip label={value} {...getItemProps()} /> : null;
3713+
}}
3714+
renderInput={(params) => <TextField {...params} autoFocus />}
3715+
/>,
3716+
);
3717+
3718+
const textbox = screen.getByRole('combobox');
3719+
3720+
fireEvent.change(textbox, { target: { value: 'on' } });
3721+
3722+
expect(() => {
3723+
fireEvent.keyDown(textbox, { key: 'ArrowLeft' });
3724+
}).not.to.throw();
3725+
3726+
expect(textbox).to.have.property('value', 'on');
3727+
expect(textbox).toHaveFocus();
3728+
});
36863729
});
36873730

36883731
it('should not shrink the input label when value is an empty array in multiple mode using renderValue', () => {

packages/mui-material/src/useAutocomplete/useAutocomplete.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -853,7 +853,7 @@ function useAutocomplete(props) {
853853
handleOpen(event);
854854
break;
855855
case 'ArrowLeft':
856-
if (!multiple && renderValue) {
856+
if (!multiple && renderValue && value != null) {
857857
focusItem(0);
858858
} else {
859859
handleFocusItem(event, 'previous');

0 commit comments

Comments
 (0)