Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
David Hellsing Avatar asked Nov 03 '16 11:11

David Hellsing


People also ask

How do you prevent default behavior of forms in React?

We can prevent this default behaviour by making a small modification to the definition of the handleSubmit function. We call a preventDefault on the event when submitting the form, and this will cancel the default event behavior (browser refresh) while allowing us to execute any code we write inside handleSubmit.

How does onSubmit work in React?

onSubmit() is an event handler attached to the form submission event <form onSubmit={onSubmit}> . React invokes onSubmit() handler when the form is submitted, i.e. the user clicks Submit button. If the form validation fails, then onSubmit() event handler is not invoked.

How do you prevent page reload on form submit in React?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.


1 Answers

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

like image 169
Jayce444 Avatar answered Oct 22 '22 14:10

Jayce444