Skip to content

useEnterSubmit

Enter to submit, Shift+Enter for newline.

A React hook for chat-style textareas: pressing Enter submits the form, while Shift+Enter inserts a newline. Ignores keystrokes during IME composition.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-enter-submit

Usage

import { useEnterSubmit } from "@/hooks/use-enter-submit";
 
function ChatForm() {
  const { formRef, onKeyDown } = useEnterSubmit();
 
  return (
    <form
      ref={formRef}
      onSubmit={(e) => {
        e.preventDefault();
        // send message
      }}
    >
      <textarea onKeyDown={onKeyDown} placeholder="Type a message…" />
      <button type="submit">Send</button>
    </form>
  );
}

onKeyDown calls formRef.current?.requestSubmit(), so native validation and onSubmit still run.

API

function useEnterSubmit(): {
  formRef: RefObject<HTMLFormElement>;
  onKeyDown: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
};

Return value