72 lines
2.2 KiB
TypeScript
72 lines
2.2 KiB
TypeScript
/* eslint-disable react-hooks/exhaustive-deps */
|
|
import { ElementType, Fragment, useEffect, useState } from 'react';
|
|
import { RegisterOptions, useFormContext, UseFormRegister } from 'react-hook-form';
|
|
|
|
import { BottomSheet } from '~/shared/ui/bottom-sheets/bottom-sheet';
|
|
import { SelectTemplate, RadioChangeProps } from '~/shared/ui/selects/select-template';
|
|
import { TextInput } from '~/shared/ui/text-input/text-input';
|
|
|
|
interface SelectProps {
|
|
placeholder: string;
|
|
labels: string[];
|
|
values: string[];
|
|
name: string;
|
|
option?: RegisterOptions<any>;
|
|
readOnly?: boolean;
|
|
onClick?: () => void;
|
|
register: UseFormRegister<any>;
|
|
classStr?: string;
|
|
}
|
|
|
|
export const Select = ({ placeholder, register, name, option, labels, values, classStr }: SelectProps) => {
|
|
const [isOpenBottomSheet, setIsOpenBottomSheet] = useState(false);
|
|
|
|
const handleCloseBottomSheet = () => {
|
|
setIsOpenBottomSheet(false);
|
|
if ((!value || value?.length < 0) && option?.required) {
|
|
setError(name, { type: 'required', message: option?.required.toString() ?? null });
|
|
}
|
|
};
|
|
|
|
const { setValue, clearErrors, watch, getValues, setError } = useFormContext();
|
|
const value = watch(name);
|
|
|
|
const defaultValue = getValues(name);
|
|
const selectedValue = watch(name, defaultValue);
|
|
const selectedLabel = labels[values.indexOf(selectedValue)];
|
|
|
|
const onInputClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
|
|
event.preventDefault();
|
|
setIsOpenBottomSheet(true);
|
|
};
|
|
|
|
const onRadioChange = ({ event }: RadioChangeProps<ElementType<typeof values>>) => {
|
|
setValue(name, event.target.value);
|
|
setIsOpenBottomSheet(false);
|
|
clearErrors(name);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (value?.length > 0) {
|
|
setValue(name, selectedValue);
|
|
}
|
|
}, []);
|
|
|
|
return (
|
|
<Fragment>
|
|
<TextInput
|
|
label={placeholder}
|
|
{...register(name)}
|
|
readOnly
|
|
onClick={onInputClick}
|
|
selectLabel={selectedLabel}
|
|
selectMode
|
|
classStr={classStr}
|
|
/>
|
|
<BottomSheet title={placeholder} open={isOpenBottomSheet} onClose={handleCloseBottomSheet}>
|
|
<SelectTemplate values={values} labels={labels} selectedLabel={selectedLabel} onRadioChange={onRadioChange} />
|
|
</BottomSheet>
|
|
</Fragment>
|
|
);
|
|
};
|