import { FocusEvent, ReactNode } from 'react'; import { FieldValues, useController, UseControllerProps } from 'react-hook-form'; import { FormControl, FormControlLabel, FormControlLabelProps, FormControlProps, FormHelperText, FormHelperTextProps, FormLabel, FormLabelProps, Radio, RadioGroup, RadioGroupProps, RadioProps } from '@mui/material'; import { isBoolean, isString, isUndefined } from 'lodash'; import { useDefaultProps } from '../../hooks'; import { useLocalization } from '../../localization'; export interface RadioOption { value: string; label: ReactNode; slotProps?: { formControlLabel: Omit; radio: RadioProps; }; } export type RHFRadioGroupProps = UseControllerProps & Omit & { label: string; options: RadioOption[]; required?: boolean; helperText?: string; onChange?: RadioGroupProps['onChange']; onBlur?: RadioGroupProps['onBlur']; slotProps?: { formLabel?: FormLabelProps; formControl?: Omit; radioGroup?: Omit; helperText?: FormHelperTextProps; formControlLabel?: Omit; }; }; function RHFRadioGroup(inProps: RHFRadioGroupProps) { const { /** React Hook Form */ name, rules, control, disabled, defaultValue, shouldUnregister, /** React Hook Form */ label, options, required, onChange, onBlur, helperText, slotProps, ...radioProps } = useDefaultProps({ name: 'ReevolveRHFRadioGroup', props: inProps }); const { translate } = useLocalization(); const { field, fieldState: { error } } = useController({ name, defaultValue, shouldUnregister, disabled, control, rules: rules && { ...rules, required: rules?.required === true ? translate('validation.required', { label }) : rules?.required } }); function onChangeHandler(event: React.ChangeEvent, value: string) { field.onChange(value); onChange?.(event, value); } function onBlurHandler(e: FocusEvent) { field.onBlur(); onBlur?.(e); } return ( {label && {label}} {options.map((option) => ( } /> ))} {(error?.message || helperText) && ( {error?.message || helperText} )} ); } declare module '@mui/material' { interface Components { ReevolveRHFRadioGroup?: { defaultProps?: Partial; }; } } export default RHFRadioGroup;