27

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.

1
  • use onKeyDown handler and check for event.keyCode, it will work. Working Fiddle Commented Dec 14, 2017 at 8:59

4 Answers 4

56

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.

Sign up to request clarification or add additional context in comments.

7 Comments

we can directly call the submit function also newComment(), instead of ref :)
@MayankShukla, true. I can't see that function anywhere in op code, so I excluded that bit.
@Chris, as you mentionned yourself, uncontrolled is one of two ways of handling texteareas in React. The question was "How can I make a form submit when a user pressed 'enter' in a textarea?", and you answer here is how to do it for uncontrolled forms. So I'd say answer is incomplete, isn't it ? :D
@CyrilCHAPON sorry for late answer. The solution wouldn't vary for controlled forms either.
oh that's right. I will check carefully again
|
11

With react 17 this does not seem to work anymore. Instead use requestSubmit().

The HTMLFormElement.submit() method submits a given form.

This method is similar, but not identical to, activating a form's submit button. When invoking this method directly, however:

No submit event is raised. In particular, the form's onsubmit event handler is not run.
Constraint validation is not triggered.

The HTMLFormElement.requestSubmit() method is identical to activating a form's submit button and does not have these differences.

Further reading here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

    onEnterPress = (e) => {
      if(e.keyCode == 13 && e.shiftKey == false) {
        e.preventDefault();
        this.myFormRef.requestSubmit();
      }
    }
    
    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>
      );
    }

2 Comments

Very much correct sir, accepted answer should be updated. Thanks.
This works in 2024
3

This snippet based on previous responses could be useful:

export const SubmitOnEnterTextArea = (
  props: React.TextareaHTMLAttributes<HTMLTextAreaElement>,
) => (
  <textarea
    {...props}
    onKeyDown={(e) => {
      if (e.key === "Enter" && !e.shiftKey && "form" in e.target) {
        e.preventDefault();
        (e.target.form as HTMLFormElement).requestSubmit();
      }
    }}
  ></textarea>
);

Comments

0

For functional component edit form element as requirements

  const functionalComponent = () => {
  const addData = () => {
    localStorage.setItem("anyitem","anyData")
  }

  EnterPress = (e) => {
    if (e.keyCode == 13 && e.shiftKey == false) {
      e.preventDefault();
      addData();
    }}
    return (
      <>
      <textarea type="text" rows="3" name="body" onKeyDown={EnterPress} />
      </>
    );
  }

1 Comment

Please add some more details do not post code only answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.