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.
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 (
handleSubmit) to your form via
handleBlurwork exactly as expected--they use a
idattribute to figure out which field to update.
Formik comes with these handy built-in event handles, (
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
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:
Overview | Formik
Let's face it, forms are really verbose in React. To make matters worse, most form helpers do wayyyy too much magic and…