From 2350d50b3eb3d0a08498180b556c8c34d50ae978 Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Mon, 23 Sep 2024 18:40:22 +0200 Subject: [PATCH] Add useFormSubmit hook to ease forms submit override. --- package.json | 2 +- src/Utils.tsx | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 45cbd54..d0ea7dc 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "1.2.6", + "version": "1.3.0", "name": "@kernelui/core", "description": "Kernel UI Core.", "scripts": { diff --git a/src/Utils.tsx b/src/Utils.tsx index 6147e56..48dd5e7 100644 --- a/src/Utils.tsx +++ b/src/Utils.tsx @@ -1,4 +1,4 @@ -import {useEffect, useRef} from "react"; +import React, {FormEvent, useCallback, useEffect, useRef} from "react"; export type Modify = Omit & R; @@ -50,3 +50,18 @@ export function usePreviousValue(currentValue: T): T // Get the previous value. return ref?.current ?? undefined; } + +/** + * Create a callback for a form submit function that fully overrides default form behavior. + * @param submitFunction The function to call on form submit. + */ +export function useFormSubmit(submitFunction: () => void): React.FormEventHandler +{ + // Use a memoized callback. + return useCallback((event: React.FormEvent) => { + // Prevent default behavior, then call submit function. + event.preventDefault(); + submitFunction(); + return false; + }, [submitFunction]); +}