Skip to content

Instantly share code, notes, and snippets.

@bryanltobing
Created June 9, 2022 13:46
Show Gist options
  • Save bryanltobing/f0fc5d95116bb712e21eef2c1879f96d to your computer and use it in GitHub Desktop.
Save bryanltobing/f0fc5d95116bb712e21eef2c1879f96d to your computer and use it in GitHub Desktop.
import {
TextField,
Autocomplete,
AutocompleteProps,
UseAutocompleteProps,
} from "@mui/material";
import React, { memo } from "react";
import { Control, Controller, Path } from "react-hook-form";
type UseAutoCompleteNarrowed<T> = UseAutocompleteProps<
T,
undefined,
undefined,
undefined
>;
export type HookFormAutoCompleteProps<TFormValues, UAutoComplete> = {
control: Control<TFormValues, any>;
name: Path<TFormValues>;
loading: boolean;
options: UseAutoCompleteNarrowed<UAutoComplete>["options"];
getOptionLabel: UseAutoCompleteNarrowed<UAutoComplete>["getOptionLabel"];
isOptionEqualToValue: UseAutoCompleteNarrowed<UAutoComplete>["isOptionEqualToValue"];
onInputChange: UseAutoCompleteNarrowed<UAutoComplete>["onInputChange"];
inputValue: UseAutoCompleteNarrowed<UAutoComplete>["inputValue"];
};
const HookFormAutoComplete = <
TFormValues extends Record<string, any>,
UAutoComplete
>(
props: HookFormAutoCompleteProps<TFormValues, UAutoComplete>
) => {
const {
control,
name,
loading,
options,
getOptionLabel,
isOptionEqualToValue,
onInputChange,
inputValue,
} = props;
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, value } }) => (
<Autocomplete
value={value}
onChange={(_evt, newValue) => onChange(newValue)}
options={options}
renderInput={params => <TextField {...params} />}
renderOption={(optionProps, option) => (
<li {...optionProps} key={JSON.stringify(option)}>
{getOptionLabel && getOptionLabel(option)}
</li>
)}
getOptionLabel={getOptionLabel}
isOptionEqualToValue={isOptionEqualToValue}
loading={loading}
onInputChange={onInputChange}
// inputValue={inputValue}
/>
)}
/>
);
};
const HookFormAutoCompleteMemo = memo(
HookFormAutoComplete
) as typeof HookFormAutoComplete;
export { HookFormAutoCompleteMemo as HookFormAutoComplete };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment