Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit nested form in Formik

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!

like image 602
Khaos101 Avatar asked Oct 15 '25 20:10

Khaos101


1 Answers

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>
  </>
);
like image 52
Umang Khandelwal Avatar answered Oct 17 '25 08:10

Umang Khandelwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!