URL: https://codesandbox.io/s/modest-feistel-o8jrv?file=/src/App.tsx

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]);

Demo here

The important bit is the event.key === "Enter" && event.metaKey statement. I hope it helps.

Comments

Šime Vidas

Hm, browsers don’t seem to do this by default.

Your email will never ever be published.

Previous:
My site's now NextJS - And I (almost) regret it already December 17, 2021 Django, Node, React, JavaScript
Next:
Make your NextJS site 10-100x faster with Express caching February 18, 2022 Node, Nginx, React, JavaScript
Related by category:
Switching from Next.js to Vite + wouter July 28, 2023 React
How to SSG a Vite SPA April 26, 2025 React
An ideal pattern to combine React Router with TanStack Query November 18, 2024 React
How to handle success and failure in @tanstack/react-query useQuery hook September 16, 2024 React
Related by keyword:
Vertically expanding textarea input boxes September 19, 2007 JavaScript
Changing the size of a textarea box August 18, 2004 Web development
Same but new keyboard, lovely change January 21, 2004 Mathematics
Labels in HTML forms January 26, 2004 Web development