Formik + Yup

Leveraging React Context

1 import React from 'react';
2 import { useFormik } from 'formik';
3
4 // Create empty context
5 const FormikContext = React.createContext({});
6
7 // Place all of what’s returned by useFormik into context
8 export const Formik = ({ children, ...props }) => {
9 const formikStateAndHelpers = useFormik(props);
10 return (
11 <FormikContext.Provider value={formikStateAndHelpers}>
12 {typeof children === 'function'
13 ? children(formikStateAndHelpers)
14 : children}
15 </FormikContext.Provider>
16 );
17 };
Our code above is again very explicit about exactly what Formik is doing. onChange -> handleChange, onBlur -> handleBlur, and so on. However, we still have to manually pass each input this "prop getter" getFieldProps(). To save you even more time, Formik comes with -powered API/components to make life easier and code less verbose: <Formik />, <Form />, <Field />, and <ErrorMessage />. More explicitly, they use React Context implicitly to connect with the parent <Formik /> state/methods.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.