So common now. You have focus inside a <textarea>
and you want to submit the form. By default, your only choice is to reach for the mouse and click the "Submit" button below, or use Tab to tab to the submit button with the keyboard.
Many sites these days support Command-Enter as an option. Here's how you implement that in React:
const textareaElement = textareaRef.current;
useEffect(() => {
const listener = (event: KeyboardEvent) => {
if (event.key === "Enter" && event.metaKey) {
formSubmit();
}
};
if (textareaElement) {
textareaElement.addEventListener("keydown", listener);
}
return () => {
if (textareaElement) {
textareaElement.removeEventListener("keydown", listener);
}
};
}, [textareaElement, formSubmit]);
The important bit is the event.key === "Enter" && event.metaKey
statement. I hope it helps.
Comments
Hm, browsers don’t seem to do this by default.