Reputation: 85
I am new to REACT-HOOK-FORM. I have created a profile page where I need to create two separate forms. Once for "Change Password" and another for "Profile Change". I am struggling in creating two separate forms via REACT-HOOK-FORM and utilizing that for providing validations.
const { handleSubmit, errors, control, reset, setValue } = useForm({
mode: "onSubmit",
reValidateMode: "onChange",
defaultValues: "",
validateCriteriaMode: "all",
submitFocusError: true,
nativeValidation: false,
});
Do I need to perform some edits in the above code? Please help.
Upvotes: 6
Views: 13438
Reputation: 840
You need to create a copy of the "useForm" in the following way
const { handleSubmit, errors, control, reset } = useForm({
mode: "onSubmit",
reValidateMode: "onChange",
defaultValues: "",
validateCriteriaMode: "all",
submitFocusError: true,
nativeValidation: false,
});
const {
handleSubmit: handleSubmit1,
errors: errors1,
control: control1,
reset: reset1,
} = useForm({
mode: "onSubmit",
reValidateMode: "onChange",
defaultValues: "",
validateCriteriaMode: "all",
submitFocusError: true,
nativeValidation: false,
});
Now basically you can create two forms under your render function like following
<>
<form onSubmit={handleSubmit(onProfileChange)} noValidate autoComplete="off">
{/* Reference "error" and "control" variable to validate your form fields */}
</form>
<form
form
onSubmit={handleSubmit1(onProfileChange)}
noValidate
autoComplete="off"
>
{/* Reference "error1" and "control1" variable to validate your form fields */}
</form>
</>;
Now you can have two different forms on the same page validated by react-hook-form without handling too many state variables.
Upvotes: 5
Reputation: 301
This is the correct answer. See how i destructured the objects
const {
register,
handleSubmit,
watch,
errors,
setValue,
setError,
control,
formState: { isSubmitting, isValid },
} = useForm({
resolver: yupResolver(schema()),
mode: "onTouched",
defaultValues: {},
});
const {
register:register1,
handleSubmit:handleSubmit1,
watch:watch1,
errors:errors1,
setValue:setValue1,
setError:setError1,
control:control1,
} = useForm({
resolver: yupResolver(schema1()),
mode: "onTouched",
defaultValues: {},
});
Upvotes: 8