|
1 | | -export const Form = (): JSX.Element => { |
2 | | - return <></> |
| 1 | +import { |
| 2 | + Controller, |
| 3 | + FieldValues, |
| 4 | + FormProvider, |
| 5 | + UseFormReturn, |
| 6 | + useFormContext, |
| 7 | +} from 'react-hook-form' |
| 8 | + |
| 9 | +import { CheckboxInput, RadioInput } from '@/components/common/input' |
| 10 | +import { CheckboxInputProps } from '@/components/common/input/CheckboxInput' |
| 11 | +import { RadioInputProps } from '@/components/common/input/RadioInput' |
| 12 | + |
| 13 | +interface FormProps<TFieldValues extends FieldValues> |
| 14 | + extends React.FormHTMLAttributes<HTMLFormElement> { |
| 15 | + methods: UseFormReturn<TFieldValues> |
| 16 | + children: React.ReactNode |
3 | 17 | } |
| 18 | + |
| 19 | +export const Form = <TFieldValues extends FieldValues>({ |
| 20 | + methods, |
| 21 | + children, |
| 22 | + ...props |
| 23 | +}: FormProps<TFieldValues>): JSX.Element => { |
| 24 | + return ( |
| 25 | + <FormProvider {...methods}> |
| 26 | + <form {...props}>{children}</form> |
| 27 | + </FormProvider> |
| 28 | + ) |
| 29 | +} |
| 30 | + |
| 31 | +const Checkbox = ({ |
| 32 | + name, |
| 33 | + rules, |
| 34 | + options, |
| 35 | + ...props |
| 36 | +}: { |
| 37 | + name: string |
| 38 | + rules?: Record<string, unknown> |
| 39 | + options: string[] |
| 40 | +} & CheckboxInputProps): JSX.Element => { |
| 41 | + const { control } = useFormContext() |
| 42 | + return ( |
| 43 | + <Controller |
| 44 | + name={name} |
| 45 | + control={control} |
| 46 | + rules={rules} |
| 47 | + render={({ field }) => ( |
| 48 | + <> |
| 49 | + {options.map(value => ( |
| 50 | + <CheckboxInput |
| 51 | + key={value} |
| 52 | + {...props} |
| 53 | + value={value} |
| 54 | + checked={field.value?.includes(value)} |
| 55 | + onChange={e => { |
| 56 | + const newValue = e.target.checked |
| 57 | + ? [...field.value, value] |
| 58 | + : field.value.filter((v: string) => v !== value) |
| 59 | + field.onChange(newValue) |
| 60 | + }} |
| 61 | + /> |
| 62 | + ))} |
| 63 | + </> |
| 64 | + )} |
| 65 | + /> |
| 66 | + ) |
| 67 | +} |
| 68 | + |
| 69 | +const Radio = ({ |
| 70 | + name, |
| 71 | + rules, |
| 72 | + options, |
| 73 | + ...props |
| 74 | +}: { |
| 75 | + name: string |
| 76 | + rules?: Record<string, unknown> |
| 77 | + options: string[] |
| 78 | +} & RadioInputProps): JSX.Element => { |
| 79 | + const { control } = useFormContext() |
| 80 | + return ( |
| 81 | + <Controller |
| 82 | + name={name} |
| 83 | + control={control} |
| 84 | + rules={rules} |
| 85 | + render={({ field }) => ( |
| 86 | + <> |
| 87 | + {options.map(value => ( |
| 88 | + <RadioInput |
| 89 | + key={value} |
| 90 | + {...props} |
| 91 | + value={value} |
| 92 | + checked={field.value === value} |
| 93 | + onChange={() => field.onChange(value)} |
| 94 | + /> |
| 95 | + ))} |
| 96 | + </> |
| 97 | + )} |
| 98 | + /> |
| 99 | + ) |
| 100 | +} |
| 101 | + |
| 102 | +Form.Checkbox = Checkbox |
| 103 | +Form.Radio = Radio |
0 commit comments