How to get formik props from children component?

Viewed 1963

I have Formik form and need in some way get Formik props (specifically serFieldError) from inner to the outer scope.

My code:

const SignUp = props => {
  const onSubmitClick = values => {
    //...
  };

  const SignUpView = props => {
    const { setFieldError } = props;

    //..

    return (
    <Form className="signup-form"/>
    //...
    );
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={signUpSchema}
      onSubmit={onSubmitClick}
      render={SignUpView}
    />
  );
};

Is there any way to pass setFieldError from SignUpView (inner) into SignUp (outer)?

1 Answers

Here's modified code based on yours. See inline comments

const SignUp = props => {
  let setFieldErrorParentReference = null;

  // This method's signature is wrong, it gets an object containing 'values' property in it. Although it may work but you are mixing up (shadowing) with props passed to your SignUp component
  // Here's proper signature https://jaredpalmer.com/formik/docs/api/formik#onsubmit-values-values-formikbag-formikbag-void
  const onSubmitClick = values => {
    //...
  };

  const SignUpView = props => {
    const { setFieldError } = props;
    // Every time SignUpView renders it will get new formik object and then that new object reference will be stored and you can do whatever you want using that.
    setFieldErrorParentReference = setFieldError;

    //..

    return (
    <Form className="signup-form"/>
    //...
    );
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={signUpSchema}
      onSubmit={onSubmitClick}
      render={SignUpView}
    />
  );
};
Related