import * as React from 'react'; import FormHelperText from '@mui/material/FormHelperText'; import { Controller, useFormContext } from 'react-hook-form'; import Autocomplete, { AutocompleteProps } from '@mui/material/Autocomplete'; interface ControlledAutocompleteProps extends AutocompleteProps { shouldUnregister?: boolean; name: string; required?: boolean; description?: string; } type Option = { label: string; value: string; } const getOption = (options: readonly Option[], value: string) => options.find(option => option.value === value); function ControlledAutocomplete(props: ControlledAutocompleteProps): React.ReactElement { const { control } = useFormContext(); const { required = false, name, defaultValue, shouldUnregister, onBlur, onChange, description, ...autocompleteProps } = props; if (!autocompleteProps.options) return (); return ( (
{/* encapsulated with an element such as div to vertical spacing delegated from parent */} { const typedSelectedOption = selectedOption as Option; if (typedSelectedOption?.value) { controllerOnChange(typedSelectedOption.value); } else { controllerOnChange(typedSelectedOption); } onChange?.(event, selectedOption, reason, details); }} onBlur={(...args) => { controllerOnBlur(); onBlur?.(...args); }} ref={ref} /> {description}
)} /> ); } export default ControlledAutocomplete;