React prevent form submission when enter is pressed inside input
You need to create a form handler that would prevent the default form action.
The simplest implementation would be:
<form onSubmit={e => { e.preventDefault(); }}>
But ideally you create a dedicated handler for that:
<form onSubmit={this.submitHandler}>
with the following implementation
submitHandler(e) {
e.preventDefault();
}
In a React component with a Search input field, nested in a larger (non-React OR React) form, this worked best for me across browsers:
<MyInputWidget
label="Find"
placeholder="Search..."
onChange={this.search}
onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}
value={this.state.searchText} />
(e)=>{e.target.keyCode === 13}
(@DavidKamer's answer) is incorrect: You don't want the event.target.
That's the input field. You want the event itself. And in React (specifically 16.8, at the moment), you want event.key
(e.key, whatever you want to call it).
I'm not sure if this works for every situation, as when you press enter in a form's input field you will still trigger the onSubmit method, although the default submit won't occur. This means that you will still trigger your pseudo submit action that you've designed for your form. A one liner with ES6 that solves the problem specifically and entirely:
<input onKeyPress={(e)=>{e.target.keyCode === 13 && e.preventDefault();}} />
This solution should have 0 side effects and solves the problem directly.