Skip to content

Commit a8b0377

Browse files
fix: escape button press doesn't reset the state of Autosuggest component (#172)
* Fix Autosuggest escape press handling * Add appropriate unit test
1 parent 94a306f commit a8b0377

2 files changed

Lines changed: 17 additions & 16 deletions

File tree

src/components/Autosuggest/Autosuggest.js

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,7 @@ class Autosuggest extends React.Component {
6060
};
6161

6262
handleInputKeyDown = event => {
63-
const { getSuggestions, onSelectionChange, selectedSuggestions } = this.props;
64-
const { inputValue } = this.state;
63+
const { onSelectionChange, selectedSuggestions } = this.props;
6564

6665
if (
6766
event.key === BACKSPACE_KEY &&
@@ -75,20 +74,11 @@ class Autosuggest extends React.Component {
7574
this.inputRef.current.blur();
7675
this.handleBlur();
7776
} else if (event.key === ESCAPE_KEY) {
78-
const getSuggestionsIsFunc = typeof getSuggestions === 'function';
79-
const suggestions = getSuggestionsIsFunc ? getSuggestions(inputValue) : getSuggestions;
80-
81-
// prevents key propagation if the dropdown is opened so escape press will close
82-
// otherwise let it go so pressed key could have an affection on the parent component
83-
// e.g. close modal window
84-
if (suggestions && suggestions.length) {
85-
this.inputRef.current.blur();
86-
this.inputRef.current.parentElement.focus();
87-
event.stopPropagation();
88-
} else {
89-
this.inputRef.current.blur();
90-
this.handleBlur();
91-
}
77+
// prevents key propagation and sets the focus on parent component
78+
this.inputRef.current.blur();
79+
this.handleBlur();
80+
this.inputRef.current.parentElement.focus();
81+
event.stopPropagation();
9282
}
9383
};
9484

src/components/Autosuggest/__tests__/Autosuggest.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,17 @@ describe('Autosuggest', () => {
179179
expect(blurSpy).toHaveBeenCalled();
180180
expect(mockOnBlur).toHaveBeenCalled();
181181
});
182+
it('should clear input value on pressing Escape button', () => {
183+
const textInputValue = 'driver';
184+
185+
wrapper.find('input').simulate('change', { target: { value: textInputValue } });
186+
187+
expect(wrapper.find('input').props().value).toEqual(textInputValue);
188+
189+
wrapper.find('input').simulate('keyDown', { key: 'Escape' });
190+
191+
expect(wrapper.find('input').props().value).toEqual('');
192+
});
182193
it('should blur on pressing Tab button', () => {
183194
const inputEl = instance.inputRef.current;
184195
const blurSpy = jest.spyOn(inputEl, 'blur');

0 commit comments

Comments
 (0)