Jason Bourne Jason Bourne - 4 years ago 408
React JSX Question

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

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) {
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>

Answer Source

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

Edit: As James says in the comments you could also call event.preventDefault() in the callback to stop the page trying to load the action url.

If you want to use this in the callback you could use arrow functions: onSubmit={(e) => this.onCommentSubmit(e)} or this.onCommentSubmit = this.onCommentSubmit.bind(this) in the constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download