Reputation: 794
I am using react-hook-form in my application,and I used autocomplete in react-hook-form.
My autocomplete has dropdown values like 1988, 1987, 1986, I thought that I need not use onchange event for this autocomplete and when I select 1988 from the dropdown, that value gets passed by react-hook-form without using onchange event. , However, when I select a value from autocomplete and submit the react-hook-form, 0 is being passed as param instead of the actual value.
I know that we can use onChange event and set the selected dropdown value into the state, however I am not thinking of doing any state management for the form variables because react-hook-form interally uses state management and sends the data automatically on submitting the form. Below is my code. May I know if using the onChange event and then setting the selected dropdown value to state is the only solution to this?
export default function RegistratioinForm() {
const { handleSubmit, control } = useForm();
const handleSubmit = (data) => {
console.log(data) (here in this data, I am seeing 0 as being passed, instead of the selected values 1988 or 1987 or 1986
}
const options = [1988, 1987, 1986]
return(
<form className={classes.root} onSubmit={handleSubmit(onSubmit)}>
<Grid
<AutoComplete
options={options}
control={control}
name="year"
label="Select Year" (I am not using onchange event expecting that react-hook-form sends the selected dropdown value directed, however 0 is being passed when I select any one of the dropdown values.)
/>
);
Upvotes: 1
Views: 345
Reputation: 2661
You need to use Controller
from react-hook-form.
What Autocomplete-Component are you using? This example assumes you're using Autocomplete from @material-ui/lab
:
<Controller
name={"year"}
control={control}
render={({ field: { onChange, ...controllerProps } }) => (
<Autocomplete
{...controllerProps}
onChange={(e, data) => onChange(data)}
options={options}
getOptionLabel={(option) => option.title}
renderInput={(params) => <TextField {...params} label="Select Year" />}
)}
/>
)}
/>
Upvotes: 1