Search code examples
reactjsformsparentformikprop

Passing a Formik prop from a Form to a Child component


I'm trying to modularize as much as I can a Formik huge formulary and I'm having some trouble dealing with the onSubmit function. I'm not sure how to pass Formik's (resetForm) prop to the child component, any suggestions?

(I simplified the following code, since dealing with resetForm is the only problem I found)

Code:

    <Formik
      initialValues={formInitialValues}

      validate={values => formValidators(values)}

      onSubmit={(values, { resetForm }) => {
        dispatch(postCreate(values))
        resetForm()
      }}
    >

What I want to do is something similar to what I did with "validate".


Solution

  • Component <Formik>'s child function has single argument props, which includes handleReset():

    In the following example, handleReset() is destructured and passed into another child.

    <Formik
      initialValues={{ name: "" }}
      onSubmit={async values => {
        // dispatch(postCreate(values))
        console.log({values})
      }}
    >
      {({
          values,
          dirty,
          isSubmitting,
          handleChange,
          handleSubmit,
          handleReset
        }) => {
        return (
          <form onSubmit={handleSubmit}>
            <input
              id="name"
              type="text"
              value={values.name}
              onChange={handleChange}
            />
            <button
              type="button"
              className="outline"
              onClick={handleReset}
              disabled={!dirty || isSubmitting}
            >
              Reset
            </button>
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </form>
        );
      }}
    </Formik>
    

    Live Demo