How to build Better React Forms with Formik

With the problem of form context solved with Formik, developers are free to focus on the behaviour they are aiming to achieve from their forms.
In this post, we’ll look at how we can build better React forms with Formik. Formik is a small library that helps you with the three major React form issues:

  1. Handling values in form state
  2. Validation and error messages
  3. Managing form submission

By fixing all of the above, Formik keeps things organized, thereby making testing, refactoring and reasoning about your forms a breeze. We’ll look at how Formik helps developers build better React forms while handling those three issues.

Installation

You can install Formik with NPM, Yarn or a good ol’ <script> via unpkg.com.

NPM

$ npm install formik --save	

YARN

 yarn add formik

Formik is compatible with React v15+ and works with ReactDOM and React Native.
You can also try before you buy with this demo of Formik on CodeSandbox.io

CDN

If you’re not using a module bundler or package manager, Formik also has a global (“UMD”) build hosted on the unpkg.com CDN. Simply add the following script tag to the bottom of your HTML file:

<script src="https://unpkg.com/formik/dist/formik.umd.production.js"></script>

Handling Values in Form State

Let’s look at how Formik handles one of the major React form issues of passing values around in React forms.

Consider an example where we have two input fields for email and password. We want to log the values of these fields to the console when the form is submitted. With the usual React form, we can create this form like so:

 import React, { Component } from 'react';
    class App extends Component {
    constructor(){
      super()
      this.state = {
        email: '',
        password: ''
      }
      this.handleEmailInput = this.handleEmailInput.bind(this)
      this.handlePasswordInput = this.handlePasswordInput.bind(this)
      this.logValues = this.logValues.bind(this)
    }
      logValues (){
        console.log(this.state.email);
        console.log(this.state.password);
      };
      handleEmailInput (e) {
        this.setState({ email: e.target.value });
      };
      handlePasswordInput (e) {
        this.setState({ password: e.target.value });
      };
      render() {
        return (
          <form onSubmit={this.logValues} >
            <input type="email" onChange={this.handleEmailInput}
	value={this.state.email}
	placeholder="Email"
            />    
            <input type="password" onChange={this.handlePasswordInput}
	value={this.state.password}
	placeholder="Password"
            />
            <button onClick={this.logValues}> Log Values </button>
          </form>
        );
      }
    }
    export default App;

Here, you’ll notice that we have a state object that manages the state of the form. We’ve also defined handlers to manage the state of the input fields, the values, the changes and so on. This is the conventional way of creating forms in React, so let’s skip all the explanations and get to the Formik part.

With Formik, this could be better, even neater and, oh, done with less code. Now let’s try recreating this exact functionality with Formik:

import React from 'react'
    import { withFormik, Form, Field } from 'formik'
    
      const App = ({
        values,
        handleSubmit,
      }) => (
        <Form>
          <Field type="email" name="email" placeholder="Email"/>
          <Field type="password" name="password" placeholder="Password"/>
          <button>Submit</button>
        </Form>
        )
      const FormikApp = withFormik({
        mapPropsToValues({ email, password}) {
          return {
            email: email || '',
            password: password || '',
          }
      },
        handleSubmit(values){
        console.log(values)
        }
      })(App)
      
    export default FormikApp;

Did you notice how clean and simple it was to recreate the form with Formik? Yeah, you did. Now, let’s walk you through it. Here, we used withFormik() to create the FormikApp component. WithFormik takes in an option, which, according to Formik docs, is a list of objects that we can pass into the withFormik() method to define its behavior.

In this case, we have passed in the mapPropsToValues({ }) option as a function which itself takes in the values of the input fields and passes them as props to our App component. In the App component we can access the values of all the input fields simply by destructuring it and passing in the Formik props called values, which is just an object with a bunch of key/value pairs.

With Formik, we don’t have to define an onChange handler or even an onSubmit on the form, it all comes built-in. All we have to do is import the Form prop from Formik and destructure it in the App component. With that done, we can use it to create our form fields.

Finally, with Formik, we don’t have to define a value in the input field. We simply import the Field prop provided by Formik and it saves us the stress of all those boilerplate codes.

Validation and Error Messages

In React, there is no simple way to handle validation in forms as at this time. Don’t get me wrong, there are good ways — just not as simple as Formik makes it. If you have created a sign-up form before in React, you’ll understand that you had to write your own validation logic to make sure users comply to your standards. You probably had to write a lot of code to validate the email input field, password, number, date and even your own error messages.

With Formik, we can use Yup to handle all that. It is so simple that you can implement standard validation in your input fields in less than 10 lines of code. That’s not all. It also allows you to define your custom error messages for every field condition you check.

Continuing from our last Formik form example, let’s validate the email and password fields with Yup:

import React from "react";
import { withFormik, Form, Field } from "formik";
import Yup from "yup";
      
      const App = ({ values, handleSubmit, errors, touched }) => (
      <Form>
        <div>
          {touched.email && errors.email && <p>{errors.email}</p>}
          <Field type="email" name="email" placeholder="Email" />
        </div>
        <div>
          {touched.password && errors.password && <p>{errors.password}</p>}
          <Field type="password" name="password" placeholder="Password" />
        </div>
        <button>Submit</button>
      </Form>
      );
      const FormikApp = withFormik({
        mapPropsToValues({ email, password }) {
          return {
          email: email || "",
          password: password || ""
        };
      },
      validationSchema: Yup.object().shape({
        email: Yup.string().email().required(),
        password: Yup.string().min(6).required()
      }),
      handleSubmit(values) {
        console.log(values);
      }
      })(App);
      export default FormikApp;

Here we have implemented validation and error reporting for both the email and password fields with the addition of about seven lines of code. How is this possible, you might ask? Well, let’s tell you how. In the FormikApp component, we passed in another option, validationSchema to withFormik({ }), which automatically handles all the validations for us.

With the errors prop we just destructured in the App component props, we now have access to the validationSchema errors. As a result, we can define a text field above the input fields to show the validation error messages to the users.

Finally, to be certain that the error messages appear only during submission (not when the user is typing), we used the touched prop. That way, we can conditionally check if a certain field has been touched. If it has, check if there are any errors; if there are, show the text when the field is submitted.

So far, if you run this App and try submitting false values, this is the output you’ll get:
This is image title

That is all well and good, but what if we wanted to provide a custom error message for the individual validation checks? With Formik, we can do this by specifying the messages inside the validationSchema methods like this:

validationSchema: Yup.object().shape({
        email: Yup.string()
          .email("Invalid Email !!")
          .required("Email is required"),
        password: Yup.string()
          .min(6, "Password must be above 6 characters")
          .required("Password is required")
      }),

At this point, the error messages will update appropriately with the contents that we have defined:
This is image title

Managing Form Submission

Formik gives us the functionality to make asynchronous requests even on submission of the form. Sometimes we’ll want to check if the submitted email address already exists in the database, and if it does we report it to the user.

Also, while the asynchronous request is running, we may want to dynamically disable the submit button until the execution completes. Formik provides us all this functionality and more. To further demonstrate this, let’s simulate a scene where, if an email address already exists, we’ll report an error to the user after the asynchronous request, which we have replaced with a timeout of two seconds. Then if the supplied email address doesn’t exist yet, we reset the form.

To do this, we’ll pass in the necessary Formik props as the second argument to the handleSubmit handler in our FormikApp component like this:

handleSubmit(values, {resetForm, setErrors, setSubmitting}) {
        setTimeout(() => {
          if (values.email === "john@doe.com") {
            setErrors({ email: 'Email already exists'})
          } else {
            resetForm()
          }
        },2000)
      }

Wonderful, now we can perform dynamic asynchronous operations while submitting forms. You may have noticed that we still have an unused argument setSubmitting, and you’re probably wondering why we have it there if we are not going to use it. Well, we are.

We’ll use it to conditionally disable our submit button when a submission operation is running. All we need to do is access a prop that is passed to our App component called isSubmitting. As the name suggests, it is a Boolean. If we are submitting, the value is true so we can do something, and if we are not, it’s false, and we can do something else.

const App = ({ values, handleSubmit, errors, touched, isSubmitting }) => (
      <Form>
        <div>
          {touched.email && errors.email && <p>{errors.email}</p>}
          <Field type="email" name="email" placeholder="Email" />
        </div>
        <div>
          {touched.password && errors.password && <p>{errors.password}</p>}
          <Field type="password" name="password" placeholder="Password" />
        </div>
          <button disabled={isSubmitting}>Submit</button>
      </Form>
      );

Then in the handleSubmit handler, we just set setSubmitting to false:

handleSubmit(values, {resetForm, setErrors, setSubmitting}) {
        setTimeout(() =>{
          if (values.email === "john@doe.com") {
          setErrors({ email: 'Email already exists'})
        } else {
        resetForm()
        }
        setSubmitting(false)
        },2000)
      }

Now whenever a submit operation is running, the submit button is conditionally disabled until the asynchronous operation is done executing.

Conclusion

This is Formik at the barest minimum. There are a ton of things you can do with Formik that we didn’t touch in this post. You can go ahead and find out more yourself in the documentation and see how you can optimize the React forms in your existing application or how to implement these amazing features in your subsequent React apps. Compared to the conventional way of creating forms in React, Formik is a must have.

Learn More

#reactjs #javascript

How to build Better React Forms with Formik
8 Likes180.20 GEEK