Search code examples
reactjsformsevent-bubbling

Pressing enter while focused on input causes sibling button to fire


In a react app, there's a form with some buttons and input as below:

<form>
  <div>
    {
      ['1', '10', '100'].map(val => (
        <button onClick={() => console.log(val)}>
          {val}
        </button>
    }
  </div>
  <div>
    <input type='string' /> 
  </div>
</form>

When focused on the input field, pressing 'Enter' causes the first button to fire (console.log('1')).

It seems related to some default form behaviour, as changing <form> element to <div>, fixes the issue.

And adding event.preventDefault() to the input's onKeyDown handler also fixes the issue, which suggests there is some event bubbling involved.

From my understanding, pressing 'Enter' when focused on input field in a form causes form submission, and event bubbling should only trigger parent handlers, so this is quite confusing to me that the first button, which is in a sibling element would be triggered


Solution

  • Yes, that's right, there is type property in the button element - https://www.w3schools.com/jsref/prop_pushbutton_type.asp Also, you can get noticed the default type property is submit, so it means button could be fired when pressing enter key.

    I think you can resolve the issue by setting the type property to button like below.

    <button type="button" />