-
Notifications
You must be signed in to change notification settings - Fork 0
/
form-field-wrapper.tsx
86 lines (75 loc) · 2.81 KB
/
form-field-wrapper.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use client";
import { type ReactElement, createContext, useCallback } from "react";
import { ControllerFieldState, ControllerRenderProps, FieldValues, Path, UseFormReturn, UseFormStateReturn } from "react-hook-form";
import { FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription } from "../../../ui/form";
import { cn } from "../../utils/cn";
export interface FormFieldOverviewProps<T extends FieldValues> {
label?: string;
withError?: boolean;
customControl?: boolean;
formFieldDescription?: string | ((form: UseFormReturn<T>) => string);
classNames?: {
formItem?: string;
formMessage?: string;
formLabel?: string;
formDescription?: string;
formControl?: string;
}
}
export interface FormFieldContextProps<T extends FieldValues> {
field: ControllerRenderProps<T, Path<T>>;
fieldState: ControllerFieldState;
formState: UseFormStateReturn<T>;
}
interface FormFieldWrapperProps<T extends FieldValues> extends FormFieldOverviewProps<T> {
form: UseFormReturn<T>;
name: Path<T>;
children: (props: FormFieldContextProps<T>) => ReactElement;
}
const FormFieldContext = createContext({});
export const FormFieldWrapper = <T extends FieldValues>(props: FormFieldWrapperProps<T>): JSX.Element => {
const { form, name, children, label, withError = true, customControl = false, formFieldDescription, classNames } = props;
let description: string = "";
if (typeof formFieldDescription === "function") {
description = formFieldDescription(form);
} else {
description = formFieldDescription || "";
}
const renderFormField = useCallback(() => (
<FormField
control={form.control}
name={name}
render={(renderProps: FormFieldContextProps<T>) => (
<FormItem className={cn("w-full", classNames?.formItem)}>
{label && (
<FormLabel className={classNames?.formLabel}>
{label}
</FormLabel>
)}
{customControl ? (
children?.(renderProps)
) : (
<FormControl className={classNames?.formControl}>
{children?.(renderProps)}
</FormControl>
)}
{withError && <FormMessage className={cn("text-rose-600", classNames?.formMessage)} />}
{formFieldDescription && (
<FormDescription className={cn("text-left flex flex-col", classNames?.formDescription)}>
{description.split("\n").map((p) => {
return (
<span key={p}>{p}</span>
);
})}
</FormDescription>
)}
</FormItem>
)}
/>
), [children, customControl, form.control, formFieldDescription, label, name, withError, classNames, description]);
return (
<FormFieldContext.Consumer>
{renderFormField}
</FormFieldContext.Consumer>
);
};