React-autosuggest: How to prevent enter from submitting the form when the suggestion list is open?

Created on 21 Aug 2017  路  3Comments  路  Source: moroshko/react-autosuggest

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?

Most helpful comment

You could add:

onSuggestionSelected = (event, { method }) => {
  if (method === 'enter') {
    event.preventDefault();
  }
};

Codepen

All 3 comments

You could add:

onSuggestionSelected = (event, { method }) => {
  if (method === 'enter') {
    event.preventDefault();
  }
};

Codepen

@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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jerrylow picture jerrylow  路  3Comments

mkaemmerer picture mkaemmerer  路  3Comments

eldyvoon picture eldyvoon  路  3Comments

AlgoTrader picture AlgoTrader  路  3Comments

luke-unifymonitor picture luke-unifymonitor  路  3Comments