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

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


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>


It's been quite a few years since this question was last answered.React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

Now we can write this:

  useEffect(() => {    const listener = event => {      if (event.code === "Enter" || event.code === "NumpadEnter") {        console.log("Enter key was pressed. Run your function.");        event.preventDefault();        // callMyFunction();      }    };    document.addEventListener("keydown", listener);    return () => {      document.removeEventListener("keydown", listener);    };  }, []);

This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.


Use keydown event to do it:

   input: HTMLDivElement | null = null;   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {      // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event      if (event.key === 'Enter') {        event.preventDefault();        event.stopPropagation();        this.onSubmit();      }    }    onSubmit = (): void => {      if (input.textContent) {         this.props.onSubmit(input.textContent);         input.focus();         input.textContent = '';      }    }    render() {      return (         <form className="commentForm">           <input             className="comment-input"             aria-multiline="true"             role="textbox"             contentEditable={true}             onKeyDown={this.onKeyDown}             ref={node => this.input = node}            />           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>         </form>      );    }