import { FC, ReactNode, useCallback, useEffect, useMemo, useState, } from 'react'; import interClass from '../helpers/inter.font'; import { clsx } from 'clsx'; import { useFormContext } from 'react-hook-form'; import { TranslatedLabel } from '../translation/translated-label'; export const CustomSelect: FC<{ error?: any; disableForm?: boolean; label: string; name: string; placeholder?: string; removeError?: boolean; onChange?: () => void; className?: string; translationKey?: string; translationParams?: Record; options: Array<{ value: string; label: string; icon?: ReactNode; }>; }> = (props) => { const { options, onChange, placeholder, className, removeError, label, translationKey, translationParams, ...rest } = props; const form = useFormContext(); const value = form.watch(props.name); const [isOpen, setIsOpen] = useState(false); const err = useMemo(() => { const split = (props.name + '.value').split('.'); let errIn = form?.formState?.errors; for (let i = 0; i < split.length; i++) { // @ts-ignore errIn = errIn?.[split[i]]; } return errIn?.message; }, [props.name, form]); const option = useMemo(() => { if (value?.value && options.length) { return ( options.find((option) => option.value === value.value) || { label: placeholder, icon: false, } ); } return { label: placeholder, }; }, [value, options]); const changeOpen = useCallback(() => { setIsOpen(!isOpen); }, [isOpen]); const setOption = useCallback( (newOption: any) => (e: any) => { form.setValue(props.name, newOption); setIsOpen(false); e.stopPropagation(); }, [] ); useEffect(() => { if (onChange) { onChange(); } }, [value]); return (
{!!label && (
)}
{!!option.icon && (
{option.icon}
)} {option.label}
{!!value && (
)}
{isOpen && (
{options.map((option) => (
{!!option.icon && (
{option.icon}
)}
{option.label}
))}
)} {!removeError && (
{(err as any) || <> }
)}
); };