As mentioned in #60277873, in order to create nested forms you must rename the methods of the nested form such as :
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
mode: "onBlur",
});
becomes :
const {
register: register2,
formState: { errors: errors2 },
handleSubmit: handleSubmit2,
} = useForm({
mode: "onBlur",
});
However, I need to use the FormProvider and I don't know how to pass methods and modify the name of the methods since we can't do :
<FormProvider {register: register2, formState: { errors: errors2 }, handleSubmit: handleSubmit2 }>
Has anyone already encountered this problem ?
Looking at the source code of react-hook-form I don't think you can do this out of the box, unless you create your own contexts and hooks
Something like this:
const MyFormCtxDefaults = {
form1: null,
form2: null,
};
const MyFormCtx = React.createContext(MyFormCtxDefaults);
const MyFormCtxProvider = (props) =>
(<MyFormCtx.Provider value={props}>{children}</MyFormCtx.Provider>);
const useMyForm = () => React.useContext(MyFormCtx);
const MyForm = () => {
const form1 = useForm(...);
const form2 = useForm(...);
return (
<MyFormCtxProvider form1={form1} form2={form2}>
<MyForm1 />
<MyForm2 />
</MyFormCtxProvider>
);
};
const MyForm1 = () => {
const {register} = useMyForm().form1;
return (
<input {...register('foo')} />
);
};
const MyForm2 = () => {
const {register} = useMyForm().form2;
return (
<input {...register('bar')} />
);
};
It's going to be a pain to maintain typescript tough, for help please see the original implementation https://github.com/react-hook-form/react-hook-form/blob/master/src/useFormContext.tsx#L4