Form validation with React using Formik and Redux

Posted on March 27, 2018

Form handling is a huge web development topic. There are almost only 2 ways to deal with form, depending on the lib / the framework you choose to use and depending on the side you are trying to handle your form (client vs server) :

The ones that include form handling a component. This component usually does a lot of magic and force you to think your form the way it is going to be handle by the component.

The ones that let you do all the work. And then, you feel like it’s a non-sens having to manage your form at such a low level by yourself

Simple use case in React

As long as you work with simple form in react, things stay pretty simple. You basically just have to worry about your onSubmit method that will call your API in order to POST form data.

Here is a basic example of a form posting a snippet (a title and a text) using React, Material UI and Redux (After posting the data, the method addSnippet dispatch an event in order to refresh another component)

The first step is to do client side validation such as : if a field is required, you’ll surely want to check if the field is not empty before calling your API. In this example we would have to do that manually. Initializing a state with the fields and then check the state before calling the API could be a good idea. But still… It takes time and can be a source of errors / bug.

The second step is to do server side validation. Aka : calling your API and check for status code > 299. Then, get the returned payload hopping there is a common schema for validation errors and map the errors sent by the API to your fields. This part is a little bit tricky and also a source of errors / bug.

Form validation made simple with Formik

Formik is a react lib that helps you do the basics with forms without introducing any magic. You can see it as a collection of tools you may need when handling forms such as : handleSubmit, handleChange, handleBlur, setErrors, ets.

You will find a commented example bellow. It took me time to understand how to properly handle errors coming from the API, so this example also document the API call. The idea is to understand the whole thing here.

This example use Formik, Redux, Yup for client side validation, and Material UI for design. The form is located in a Dialog (Dialog) that opens when the user click on the FloatingActionButton (FloatingActionButton)

Keep in mind that, in case of errors, the API is supposed to return a payload structured like :

import{postSnippet}from'../../api/snippets'import{receiveOneSnippet}from'../'exportfunctionaddSnippet(data){returnasyncfunction(dispatch){try{// If status code == 201 the API return the new created object.
constresponse=awaitpostSnippet(data);//This object is dispatch to the store in order to update another component
dispatch(receiveOneSnippet(response))}catch(err){//If status code > 299 the payload is catch here.
throwerr.errors;}}}