'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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
