useEnterSubmit

A hook that simplifies form submission on enter key press.

Usage

1 2 3 4 5 6 7 import useEnterSubmit from "@/hooks/use-enter-submit"; export default function Example() { const { formRef, onKeyDown } = useEnterSubmit(); return <form ref={formRef} onKeyDown={onKeyDown}></form>; }

Installation

npx shadcn add "https://registry.niels.foo/use-enter-submit.json"

Source

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import { type RefObject, useRef } from "react"; export default function useEnterSubmit(): { formRef: RefObject<HTMLFormElement>; onKeyDown: (event: React.KeyboardEvent<HTMLTextAreaElement>) => void; } { const formRef = useRef<HTMLFormElement>(null); const handleKeyDown = ( event: React.KeyboardEvent<HTMLTextAreaElement> ): void => { if ( event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing ) { formRef.current?.requestSubmit(); event.preventDefault(); } }; return { formRef, onKeyDown: handleKeyDown }; }