|
| 1 | +// components/form/FormSelect.tsx |
| 2 | +import * as Form from '@radix-ui/react-form'; |
| 3 | +import { Controller, useFormContext } from 'react-hook-form'; |
| 4 | +import { FormFieldProps } from '../../types/form.types'; |
| 5 | +import Select from 'react-select'; |
| 6 | +import { getNestedValue } from '@/lib/helper'; |
| 7 | +import { selectStyle } from '@/pages/helm-template/styles/helm-template.style'; |
| 8 | +import { useStyle } from '@/hooks'; |
| 9 | +import { cn } from '@/lib/utils'; |
| 10 | + |
| 11 | +interface OptionType { |
| 12 | + value: string; |
| 13 | + label: string; |
| 14 | +} |
| 15 | + |
| 16 | +interface FormSelectProps extends FormFieldProps { |
| 17 | + options: OptionType[]; |
| 18 | + placeholder?: string; |
| 19 | + isSearchable?: boolean; |
| 20 | +} |
| 21 | + |
| 22 | +export const FormSelect = ({ |
| 23 | + name, |
| 24 | + label, |
| 25 | + error, |
| 26 | + options, |
| 27 | + placeholder = 'Select...', |
| 28 | + isSearchable = true, |
| 29 | + ...props |
| 30 | +}: FormSelectProps) => { |
| 31 | + const { |
| 32 | + control, |
| 33 | + formState: { errors }, |
| 34 | + } = useFormContext(); |
| 35 | + |
| 36 | + const { darkMode } = useStyle(); |
| 37 | + |
| 38 | + const fieldError = getNestedValue(errors, name); |
| 39 | + const errorMessage = fieldError?.message as string; |
| 40 | + |
| 41 | + return ( |
| 42 | + <Form.Field |
| 43 | + className={cn('form-field relative', { |
| 44 | + 'mb-6': errorMessage, |
| 45 | + })} |
| 46 | + name={name} |
| 47 | + > |
| 48 | + {label && ( |
| 49 | + <div className="mb-2 flex items-baseline justify-between"> |
| 50 | + <Form.Label className="form-label">{label} :</Form.Label> |
| 51 | + </div> |
| 52 | + )} |
| 53 | + <Form.Control asChild> |
| 54 | + <Controller |
| 55 | + name={name} |
| 56 | + control={control} |
| 57 | + render={({ field }) => ( |
| 58 | + <Select |
| 59 | + {...field} |
| 60 | + options={options} |
| 61 | + placeholder={placeholder} |
| 62 | + className="w-full" |
| 63 | + {...props} |
| 64 | + styles={selectStyle(darkMode)} |
| 65 | + /> |
| 66 | + )} |
| 67 | + /> |
| 68 | + </Form.Control> |
| 69 | + {errorMessage && ( |
| 70 | + <div className="absolute left-0 top-full"> |
| 71 | + <Form.Message className="form-message ml-auto text-sm text-red-500"> |
| 72 | + {errorMessage} |
| 73 | + </Form.Message> |
| 74 | + </div> |
| 75 | + )} |
| 76 | + </Form.Field> |
| 77 | + ); |
| 78 | +}; |
0 commit comments