Neel Boy
Neel Boy

Reputation: 27

Can't get value form input in react-hook-form

I'm using react-hook-form.

I have a value that comes from my database that I'm using to set the input's value on initial load. When I submit the form I lose the value.

How can I fix this issue?

const FormCV = () => {
 const { register } = useForm();
 const onSubmit = (data) => {alert(JSON.stringify(data))};
 return (
   <form onSubmit={handleSubmit(onSubmit)}>
     <input
      type="text"
      value={newForm.companyname}
      {...register("companyname")}
     />
    </form>
  );
};

Upvotes: 2

Views: 5568

Answers (1)

Sean W
Sean W

Reputation: 6598

You need to remove the value prop and set the value in react-hook-form's register or defaultProps.


Option 1

Set a single value in register.

const { register } = useForm(); // don't need default values set here
<input {...register("companyname",{ value: newForm.companyname })} ...otherProps />

Option 2

Set the values for inputs using defaultValues

const defaultValues = { companyname: newForm.companyname };
const { register } = useForm({ defaultValues });
<input {...register("companyname")} ...otherProps /> // don't need to set the value here

Upvotes: 3

Related Questions