...

/

The FormikWrapper Component

The FormikWrapper Component

Learn how to create a reusable wrapper component for a form in React.

It’s important that for all the forms in our application, the styles and the way we notify users of errors need to be consistent. One way to do this is to copy the entire form code and paste it into the different pages where we need a form. But this is bad practice because whenever we want to change anything in the form, we’ll need to change it in multiple places. Besides, it’s always a bad idea to repeat ourselves, especially when we can avoid it. What we want to do instead is to build a set of reusable form components that we can apply across different forms in an app.

To get started, we’ll create a FormikWrapper component. This is what will house our Formik context provider. This makes it possible for us to add other reusable components to our form, with each of them having access to the form’s state wherever they are used.

The FormikWrapper component

The FormikWrapper component is where we’ll initialize Formik’s state using the Formik component. The Formik component houses the context provider and it accepts some props that initialize Formik’s state, including initialValues, validationSchema, and onSubmit.

Usually, in an app, there are multiple forms, such as the login form, the registration form, the forgot password ...