Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field's Formik bag empty when nested in third party component

I'm using Formik's Field component to render an input like this:

<Formik 
  initialValues={initialValues}
  onSubmit={onSubmit}
  render={formProps => (
    <Form>
      <Field name="lastName" render={({ field, form }) => (
        <input {...field} placeholder="lastName" />
      )} />
    </Form>
)} />

Here is a CodeSandbox that illustrates the issue. You'll see if you swap the product column definition with the one that just renders the product as a string rather than use a Formik input, it works fine.

In the code above, Formik seems to be "automagically" determining the Formik bag form object in the Field's render function.

This has worked without issue until I integrated my Field into a third party library, in my case, rendering it in a cell of an agGrid table. When I do this, I get TypeError: this.props.formik.registerField is not a function browser console errors. Debugging this error, I see the following in Formik's compiled code:

FieldInner.prototype.componentDidMount = function () {
  this.props.formik.registerField(this.props.name, this);
};

When I inspect this.props.formik which should be my Formik bag, it's an empty object. This is the same object I see when I put my break point in the Field's render function. When I inspect this object for instances of my Field outside of agGrid, it is the fully populated Formik bag including initialValue props, registerField function, etc.

Why is Formik not properly retrieving the Formik bag form object when my Field is nested in an agGrid table cell and how can I address this issue?

like image 813
im1dermike Avatar asked Jan 24 '19 16:01

im1dermike


People also ask

Can Formik be nested?

The name props in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore.

How do I access current value of a Formik field without submitting?

it is very simple just do console. log(formik. values) and you will get all the values without submitting it.

How do you handle error in Formik?

The way that Formik handles errors is that the returned error structure should map an error message to same structure as your values. In our case we have a single level object with a firstName key. So if our value below is set like this, then our error should map accordingly.


1 Answers

Are you using a version of React >=16? If so it looks like AgGridReact doesn't support the new version of the context API that Formik is using behind the scenes.

https://github.com/ag-grid/ag-grid-react/issues/131

Either wait for AgGridReact to release a new version, or consider downgrading to a version of React <16 so Formik falls back to the old context api.

like image 189
Jed Richards Avatar answered Oct 12 '22 21:10

Jed Richards