How to submit a form using Enter key in react.js?

Istiak Morsalin picture Istiak Morsalin · Oct 19, 2015 · Viewed 119.7k times · Source

Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?

N.B: No jquery is appreciated.

 comment: function (e) {
        e.preventDefault();
        this.props.comment({comment: this.refs.text.getDOMNode().value, userPostId:this.refs.userPostId.getDOMNode().value})
    },


 <form className="commentForm">
     <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text"  /><br />
    <input type="text" placeholder="userPostId" ref="userPostId" /> <br />
     <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
    </form>

Answer

Dominic picture Dominic · Oct 19, 2015

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>