I’m trying to pass a query arg I receive in NextJS (if it exists) as a hidden input in a react-hook-form form.
The naive implementation:
const GiveawayForm = () => {
const {
handleSubmit,
register
} = useForm();
const router = useRouter();
const referrer = router.query?.ref;
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<input id='referrer' name='referrer' type='hidden' value={referrer} {...register( 'referrer')} />
<button type='submit'>click me</button>
</form>
)
}
fails because it’s changing from uncontrolled to controlled. Simply changing
value={referrer}
to
value={referrer ? referrer : 'foo'}
fixes the error, but always ends up submitting ‘foo’, even though it correctly updates the ‘value’ field in the rendered html.
I guess I have to do something with react-hook-form’s resetField, but I’m not sure; and even if that’s true, I can’t get it to work.
If I do:
const GiveawayForm = () => {
const {
handleSubmit,
register,
resetField
} = useForm();
const router = useRouter();
const referrer = router.query?.ref;
useEffect(() => {
resetField('referrer');
}, [referrer])
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<input id='referrer' name='referrer' type='hidden' value={referrer ? referrer : ''} {...register( 'referrer')} />
<button type='submit'>click me</button>
</form>
)
}
it ends up not submitting the ‘referrer’ field at all.
What hook-fu do I need to use to be able to submit with the form a value I receive from the useRouter hook?
>Solution :
To fix the issue you’re encountering with the useForm hook, you can try removing the value attribute from your input element, and instead use the defaultValue attribute to set the initial value of the field. Then, you can use the reset method provided by useForm to reset the value of the field to the initial value whenever the referrer variable changes.
Here is an example of how you could do this:
const GiveawayForm = () => {
const {
handleSubmit,
register,
reset
} = useForm();
const router = useRouter();
const referrer = router.query?.ref;
useEffect(() => {
reset({ referrer });
}, [referrer, reset]);
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<input
id="referrer"
name="referrer"
type="hidden"
defaultValue={referrer || ''}
ref={register}
/>
<button type="submit">click me</button>
</form>
);
};
In this example, the input element uses the defaultValue attribute to set the initial value of the referrer field to the value of the referrer variable. Then, the useEffect hook is used to reset the form whenever the referrer variable changes, using the reset method provided by useForm. This sets the value of the referrer field to the new value of the referrer variable.