import { ReactNode } from "react"; import { get } from "lodash"; import { Control, FieldPath, FieldValues, useFormContext, } from "react-hook-form"; import { twMerge } from "tailwind-merge"; import { Prettify } from "@/types"; import { ErrorMessage } from "./ErrorMessage"; import { Label } from "./Label"; export type GenericFieldProps< TFieldValues extends FieldValues = FieldValues, TFieldName extends FieldPath = FieldPath, > = { name: TFieldName; control: Control; className?: string; labelClassName?: string; childrenWrapperClassName?: string; label?: React.ReactNode; hideErrorMessage?: boolean; }; type FieldProps< TFieldValues extends FieldValues = FieldValues, TFieldName extends FieldPath = FieldPath, > = Prettify< GenericFieldProps & { required?: boolean; children: ReactNode; } >; export const Field = < TFieldValues extends FieldValues = FieldValues, TFieldName extends FieldPath = FieldPath, >( props: FieldProps, ) => { const { name, className, labelClassName, childrenWrapperClassName, label, children, required, hideErrorMessage = false, // eslint-disable-next-line @typescript-eslint/no-unused-vars -- used to restrict the `name` prop type control, } = props; const form = useFormContext(); const { formState: { errors }, } = form; const hasError = name && !!get(errors, name)?.message; return (
{label ? ( ) : null}
{children}
{hideErrorMessage || !hasError ? null : ( )}
); };