Using Formik to Create Forms in React

React is great for many things; it’s pretty easy to learn and use, it allows developers to create replicable components and templates for a site, and it makes use of a virtual DOM to know which parts of the actual DOM to re-render thus boosting site performance.

One thing React isn’t great at is handling forms. If you’ve searched the web for ways to handle form validations in React before, you know what I’m talking about. One way to handle form validation in React is to set up an errorMessage key in a component’s state and set up some conditional logic that checks the input and sets that errorMessage. Something that might look like this:

This works fine, but if your form had more than one field, this approach gets overly verbose and messy pretty fast.

That’s where Formik comes in! Formik is a small but mighty React library that makes handling errors and validations incredibly easy. Formik was developed by Jared Palmer as a way to standardize the flow of form functionality. From the Formik documentation:

Formik keeps track of your form's state and then exposes it plus a few reusable methods and event handlers (handleChange, handleBlur, and handleSubmit) to your form via props. handleChange and handleBlur work exactly as expected--they use a name or id attribute to figure out which field to update.

Formik comes with these handy built-in event handles, (handleChange, handleBlur, and handleSubmit)reducing the need for a developer to create custom handleChange or handleSubmit methods that contain a bunch of conditional logic to handle error validations. Formik also comes with an initialValues prop, so you no longer need to create local state.

Formik also comes with a handy validate prop, which handles validation after user input and on submit. All you have to do is pass in the validate prop and give it a value of a callback function that handles the validation conditional logic.

The Formik library also comes with Form, Field, and ErrorMessage components. ErrorMessage will automatically display the error messages for the corresponding Field component of the same name. So a form’s setup with Formik will look like this:

Without any styling, this gives us a very simple form with errors for submitting information about your favorite pet.

In conclusion, our complete PetForm component looks like this:

Full Stack Software Engineer passionate about coding, intersectional environmentalism, and pho.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store