React Formik insert a formik form into parent formik form

Tags: , , ,



currently, I have the parent component and children component Dialog with different formik form, the brief structure which is like this

<Formik initialValues={...} onSubmit={...}>
  //some form fields here
  <Button type="submit" />
  <Button onClick={()=>{setDialogOpen(true)}}/>
  <Dialog Open={dialogOpen}>
</Formik>

<Dialog>
  <Formik initialValues={...} onSubmit={...}>
    //some form fields here
    <Button type="submit" />
  </Formik>
</Dialog>

For some reason I can’t take Dialog out of the parent formik, the issue is when I click the children’s submit button, the parents’ formik form will also be triggered, how can I avoid this?

Answer

I would think that the submit button event is bubbling to the top formik. If you use the formik hook useFormik you can then have two separate forms and call submit on each button:

import { useFormik } from 'formik';
const [parentForm] = useFormik();
const [dialogForm] = useFormik();

<Formik initialValues={...} onSubmit={...} form={parentForm}>
  //some form fields here
  <Button onClick={() => parentForm.submit()} />
  <Button onClick={()=>{setDialogOpen(true)}}/>
  <Dialog Open={dialogOpen}>
</Formik>

<Dialog>
  <Formik initialValues={...} onSubmit={...} form={dialogForm}>
    //some form fields here
    <Button onClick={() => dialogForm.submit()} />
  </Formik>
</Dialog>


Source: stackoverflow