0
votes

I have a Form component, and a Parent component which takes the form component as children:

import {Formik, Form, Field} from 'formik';
import Parent from './Parent'

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));


function App() {
  return (
    <Parent>
      <Formik
        initialValues={{
          name: 'John',
          age: 27
        }}
        onSubmit={async (values) => {
          console.log('values',values);
          await sleep(2000);
          return 'success'
        }}
      >
        <Form>
        <label htmlFor="name">Name</label>
          <Field
            type="text"
            name="name"
          />
           <label htmlFor="stuff">Age</label>
          <Field
            type="number"
            name="age"
          />
        </Form>
      </Formik>
      </Parent>

  );
}

export default App;

const Parent = (props) => {


// I would like this function to be useable
  const handleSubmit = async () => {
    const res = await onSubmit() // This should be Formik's onSubmit;
    if (res) {
      console.log('res', res);
    }
  };


  return (
    <div>
        <h1>Hello</h1>
        {props.children}
        <button type="submit">Submit Form</button>
    </div>
  );
}

export default Parent;

Of course, I could put the submit button inside of the formik form and it will trigger fine. But I would like to trigger the submit from the parent component somehow, in the handleSubmit() function. I tried triggering the children.props.onSubmit() in Parent, but that solution doesn't give any values as the onSubmit is not being triggered properly.

1

1 Answers

0
votes

The solution was to move Formik to be outside Parent, so i then have access to all of formik's functions and values using useFormikContext