Home > database >  How to lift Formik "dirty" value/state up to parent component?
How to lift Formik "dirty" value/state up to parent component?

Time:10-13

Parent Component

const Parent = () => {
 const [dirty, setDirty] = useState(false)
 return (
    <ChildComponent setDirty={setDirty} />
 ) 
}

ChildComponent.js

...
  <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={schema}>
      {({ values, setFieldValue, handleSubmit, dirty }) => {
        setDirty(dirty)
        return (
          <Form onSubmit={handleSubmit}>
...

This is giving me an error with the setState but I am getting the intended result. I am passing setDirty prop from a parent component and want to "lift" the dirty state up because the parent component is rendering a modal based on this form's dirty state.

What is the correct syntax or way to lift this dirty state up to the parent?

CodePudding user response:

You can render the ChildComponent inside the Form and pass Formik props to the child component:

const Parent = () => {
  const [dirty, setDirty] = useState(false);
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={onSubmitHandler}
      validationSchema={schema}
    >
      {({ ...formikProps }) => {
        const { values, setFieldValue, handleSubmit, dirty } = formikProps;
        setDirty(dirty);
        return;
        <Form onSubmit={handleSubmit}>
          <ChildComponent {...formikProps} />
        </Form>;
      }}
    </Formik>
  );
};

CodePudding user response:

Found the answer here: setState called in render prop is causing a react warning

I needed to wrap the setDirty in a setTimeout

  • Related