Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a form when enter is pressed in a textarea in React?

Tags:

reactjs

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.

like image 437
Evanss Avatar asked Dec 14 '17 08:12

Evanss


People also ask

How do I submit a form using Enter?

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.


1 Answers

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.

like image 118
Chris Avatar answered Oct 03 '22 01:10

Chris