new-personal-site/components/lib/form/Form.tsx
Benjamin Toby 5587024789 Updates
2025-01-05 07:25:38 +01:00

36 lines
1.1 KiB
TypeScript

import _ from "lodash";
import { DetailedHTMLProps, FormHTMLAttributes } from "react";
import { twMerge } from "tailwind-merge";
/**
* # Form Element
* @className twui-form
*/
export default function Form<T extends object = { [key: string]: any }>({
...props
}: DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> & {
submitHandler?: (e: React.FormEvent<HTMLFormElement>, data: T) => void;
}) {
const finalProps = _.omit(props, "submitHandler");
return (
<form
{...finalProps}
className={twMerge(
"flex flex-col items-stretch gap-2 w-full bg-transparent",
"twui-form",
props.className
)}
onSubmit={(e) => {
e.preventDefault();
const formEl = e.target as HTMLFormElement;
const formData = new FormData(formEl);
const data = Object.fromEntries(formData.entries()) as T;
props.submitHandler?.(e, data);
}}
>
{props.children}
</form>
);
}