I have a react autosuggest component inside a form. However, when you type something in the input, you select the desired item by arrows up and down and then you press enter to select the item, it selects the item but at the same time submits the form which is, in my opinion, definitely unwanted behaviour.
I created a very simple example: here https://codepen.io/anon/pen/eEMxKB
Type, for example, 'j', press arrow down and then enter. 'Java' will be selected but at the same time the form will be submitted as you see in the console.
How to prevent it? There's no way how to tell the autosuggest list is open so that I could manually temporarily disable submitting the form or such... What else can I do?
You could add:
onSuggestionSelected = (event, { method }) => {
if (method === 'enter') {
event.preventDefault();
}
};
@moroshko Oh, thank you! I didn't realize I could do this here.
@moroshko
You could add:
onSuggestionSelected = (event, { method }) => { if (method === 'enter') { event.preventDefault(); } };
Tried using it but didn't seems to work, I am still getting onKeyDown triggered (after onSuggestionSelected is called).
I resolved doing this to detect if the suggestion panel is open, in order to assign a different behavior to enter:
const isOpen = document.querySelector(".react-autosuggest__suggestions-container.react-autosuggest__suggestions-container--open")
Not pretty.
I would gladly do something else, but I have not been able to figure out how to.
Most helpful comment
You could add:
Codepen