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.
const onFormSubmit = e => {
e.preventDefault();
// send state to server with e.g. `window.fetch`
}
...
<form onSubmit={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.