Reputation: 1862
Component with input and button to reset input TexInputComponent
:
<input
type={type}
name={name}
ref={register}
/>
<button
type="button"
onClick={clearInput}>
Reset input
</button>
const clearInput = () => {
document.querySelector(`#${name}`).value = null;
};
I'm using TexInputComponent
inside form in another component:
<TexInputComponent
name="title"
defaultValue={data?.title}
register={register({ required: 'Title is required.' })}
error={errors.title}
/>
Now when I click submit on form react-hook-form
return me error e.g 'Title is required!'. When I writing something in TexInputComponent
, then error disapear.
The problem is when I writing text and click button to reset input. The clearInput
method is executed (this method changing value
to null
) Now should displaying error, but I thing the react hook form can't see value changing.
How I can fix it?
Upvotes: 1
Views: 3325
Reputation: 81803
Your clearInput()
doesn't work because you don't provide a unique id so it can't find the input element to reset. So change to this:
<input
id={name} // --> add this line to fix
type={type}
name={name}
ref={register}
/>
However there are other ways to easily reset the form without having to define your own reset method:
Use <input type='reset' />
to create a reset button that resets all fields in a form.
Use reset()
function from useForm
hook to reset a specific field:
const { register, reset } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First name</label>
<input type="text" name="firstName" ref={register} />
<label>Last name</label>
<input type="text" name="lastName" ref={register} />
<input type="submit" />
<button
type="button"
onClick={() => reset({ firstName: "default name" })}
>
Reset first name
</button>
</form>
);
Upvotes: 1