new-personal-site/components/lib/form/Form.tsx

36 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-01-05 06:25:38 +00:00
import _ from "lodash";
2024-12-09 15:36:17 +00:00
import { DetailedHTMLProps, FormHTMLAttributes } from "react";
import { twMerge } from "tailwind-merge";
/**
* # Form Element
* @className twui-form
*/
2025-01-05 06:25:38 +00:00
export default function Form<T extends object = { [key: string]: any }>({
2024-12-09 15:36:17 +00:00
...props
2025-01-05 06:25:38 +00:00
}: DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> & {
submitHandler?: (e: React.FormEvent<HTMLFormElement>, data: T) => void;
}) {
const finalProps = _.omit(props, "submitHandler");
2024-12-09 15:36:17 +00:00
return (
<form
2025-01-05 06:25:38 +00:00
{...finalProps}
2024-12-09 15:36:17 +00:00
className={twMerge(
"flex flex-col items-stretch gap-2 w-full bg-transparent",
"twui-form",
props.className
)}
2025-01-05 06:25:38 +00:00
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);
}}
2024-12-09 15:36:17 +00:00
>
{props.children}
</form>
);
}