1 | import { useFormContext, Controller } from 'react-hook-form';
|
---|
2 | // @mui
|
---|
3 | import TextField from '@mui/material/TextField';
|
---|
4 | import Autocomplete, { AutocompleteProps } from '@mui/material/Autocomplete';
|
---|
5 |
|
---|
6 | // ----------------------------------------------------------------------
|
---|
7 |
|
---|
8 | interface Props<
|
---|
9 | T,
|
---|
10 | Multiple extends boolean | undefined,
|
---|
11 | DisableClearable extends boolean | undefined,
|
---|
12 | FreeSolo extends boolean | undefined,
|
---|
13 | > extends AutocompleteProps<T, Multiple, DisableClearable, FreeSolo> {
|
---|
14 | name: string;
|
---|
15 | label?: string;
|
---|
16 | placeholder?: string;
|
---|
17 | helperText?: React.ReactNode;
|
---|
18 | }
|
---|
19 |
|
---|
20 | export default function RHFAutocomplete<
|
---|
21 | T,
|
---|
22 | Multiple extends boolean | undefined,
|
---|
23 | DisableClearable extends boolean | undefined,
|
---|
24 | FreeSolo extends boolean | undefined,
|
---|
25 | >({
|
---|
26 | name,
|
---|
27 | label,
|
---|
28 | placeholder,
|
---|
29 | helperText,
|
---|
30 | ...other
|
---|
31 | }: Omit<Props<T, Multiple, DisableClearable, FreeSolo>, 'renderInput'>) {
|
---|
32 | const { control, setValue } = useFormContext();
|
---|
33 |
|
---|
34 | return (
|
---|
35 | <Controller
|
---|
36 | name={name}
|
---|
37 | control={control}
|
---|
38 | render={({ field, fieldState: { error } }) => (
|
---|
39 | <Autocomplete
|
---|
40 | {...field}
|
---|
41 | onChange={(event, newValue) => setValue(name, newValue, { shouldValidate: true })}
|
---|
42 | renderInput={(params) => (
|
---|
43 | <TextField
|
---|
44 | label={label}
|
---|
45 | placeholder={placeholder}
|
---|
46 | error={!!error}
|
---|
47 | helperText={error ? error?.message : helperText}
|
---|
48 | {...params}
|
---|
49 | />
|
---|
50 | )}
|
---|
51 | {...other}
|
---|
52 | />
|
---|
53 | )}
|
---|
54 | />
|
---|
55 | );
|
---|
56 | }
|
---|