Friday, June 18, 2021

making formik-powered components that still work without formik

On my team we are making a component library, and we decided to make our components Formik aware, so that when used in a Formik context they would populate themselves, handle the onChanges, detect and show errors (using Yup validation) etc. But we also wanted them to continue to work OUT of the Formik context. But when we did so, we'd see this error in the. console:

Warning: Formik context is undefined, please verify you are calling useFormikContext() as child of a <Formik> component.

We were grabbing the Context using

import { FormikContext, useFormikContext } from 'formik';
//...
const formikContext = useFormikContext();

Weirdly we get better results (i.e. no warnings) by using React's useContext instead:

import React, { useContext } from 'react';
import { FormikContext } from 'formik';
//...
const formikContext = useContext(FormikContext);

Not quite sure why that works, but it does.

(Another small Formik point - it might be more or less obvious from the examples, but you probably want to make sure you only display contents of formik.errors['thisValue'] if formik.touched['thisValue'] is true. However, the usual submit handling will set all touched values to be true. Which seems weird at first, but makes sense in practice - that's as touched as those components are going to get!)

No comments:

Post a Comment