David David - 1 month ago 12
Javascript Question

Multiple react form inputs disables the onSubmit

I have this very simple example that works as expected:
https://jsfiddle.net/x1suxu9h/

var Hello = React.createClass({
getInitialState: function() {
return { msg: '' }
},
onSubmit: function(e) {
e.preventDefault();
this.setState({ msg: 'submitted' })
},
render: function() {
return (
<form onSubmit={this.onSubmit}>
<input type="text" />
<div>{this.state.msg}</div>
</form>
)
}
});


However, when adding another form field, the onSubmit is not triggered anymore when pressing the enter key: https://jsfiddle.net/nyvt6506/

var Hello = React.createClass({
getInitialState: function() {
return { msg: '' }
},
onSubmit: function(e) {
e.preventDefault();
this.setState({ msg: 'submitted' })
},
render: function() {
return (
<form onSubmit={this.onSubmit}>
<input type="text" />
<input type="text" />
<div>{this.state.msg}</div>
</form>
)
}
});


Am I missing the obvious here?

Answer

Normally just pressing enter while focusing a form element doesn't submit it, you would use something to specifically submit it (like a submit button or an event handler to submit it upon pressing enter)

However, by default, if there's only ONE text input in the whole form then pressing enter submits it (it's some HTML specification). However, it's good to manually handle form submission.

So if you add this:

<button type='submit' />

to your form, whether there's one or two or 50 text inputs it will still submit