How can I make a form submit when a user pressed Enter in a <textarea>
? The default behaviour is to insert a linebreak into the <textarea>
.
<form className="" onSubmit={newComment}>
<textarea type="text" rows="3" name="body" />
<button className="btn" type="submit">
Comment
</button>
</form>
Should I have an onChange
event on the <textarea>
, and in a function test to see if the Enter key was pressed? This is how I would do it with vanilla JavaScript but I couldn't find the key event in React's synthetic event.
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
Your textarea is an uncontrolled element. This is an acceptable approach, however, facebook encourages the use of controlled inputs.
Anyway, here is how to do it for uncontrolled forms:
onEnterPress = (e) => {
if(e.keyCode == 13 && e.shiftKey == false) {
e.preventDefault();
this.myFormRef.submit();
}
}
render() {
return (
<form ref={el => this.myFormRef = el} className="">
<textarea type="text" rows="3" name="body" onKeyDown={this.onEnterPress} />
<button className="btn" type="submit">
Comment
</button>
</form>
);
}
You can also use id
instead of refs
above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With