My question is: in formik, given two nested forms, can I call the onSubmit of both the forms using a button inside the most external?
As example, I have a program with a structure like:
component_A.tsx:
<Formik
initialValues={values}
onSubmit={(values) => doTheRightThing_A(values)}
>
{formik =>
<Component B />
<Button
type="primary"
onClick={formik.submitForm}
>
Save
</Button>
}
</Formik>
and component_B.tsx has:
<Formik
initialValues={question: ''}
onSubmit={(values) => doTheRightThing_B(values)}
>
{formik =>
<Field name="question" />
}
</Formik>
Pressing the save button, I want to run both doTheRightThing_A and B. Thanks in advance!
Yes you can, all you have to do is assign the formikConfig for the Form B to a ref.
const formikBRef = useRef();
const onSave = (values) => {
(values) => doTheRightThing_A(values);
formikBRef.current?.submitForm();
};
return (
<>
<Formik initialValues={values} onSubmit={onSave}>
{(formik) => (
<>
<Component B />
<Button type="primary" onClick={formik.submitForm}>
Save
</Button>
</>
)}
</Formik>
<Formik
initialValues={{ question: "" }}
onSubmit={(values) => doTheRightThing_B(values)}
innerRef={formikBRef}
>
{(formik) => <Field name="question" />}
</Formik>
</>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With