<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=490755098261949&amp;ev=PageView&amp;noscript=1">

NEW CASE STUDY: See how we built a custom digital platform for Melissa Wood Health

React TypeScript Hooks: Form validation with Formik, Yup, and Material-UI

Pratik Agashe
Author Pratik Agashe
Published On Jul 22, 2020
featured_group_20212

Introduction

Because forms are an essential component in any application, it’s good that building forms are a fairly simple task.

The easiest type of forms to handle is those with fewer total fields. Things get a little trickier when we need to add form validation, but this can also be accomplished fairly easily with the right approach.

There are many ways to handle form validations with JavaScript. In some approaches, once the user submits the form, they’ll not see all error messages once. That will be frustrating for the user. To avoid that, we prefer to highlight all required fields in the form at once. To enable such a set-up in React, there are many packages, which are explained with React class-based components.

In this post, we will focus on React TypeScript: Hooks based components. For form validation, we will use the combination of Formik and Yup, and Material-UI for form elements.

Because forms are an essential component in any application, it’s good that building forms are a fairly simple task.

The easiest type of forms to handle is those with fewer total fields. Things get a little trickier when we need to add form validation, but this can also be accomplished fairly easily with the right approach.

There are many ways to handle form validations with JavaScript. In some approaches, once the user submits the form, they’ll not see all error messages once. That will be frustrating for the user. To avoid that, we prefer to highlight all required fields in the form at once. To enable such a set-up in React, there are many packages, which are explained with React class-based components.

In this post, we will focus on React TypeScript: Hooks based components. For form validation, we will use the combination of Formik and Yup, and Material-UI for form elements.

 

Formik

In long forms, keeping track of values, errors, and visited fields, and then orchestrating validations, can be a hassle. That’s where Formik comes in. Using Formik means we will spend very little time managing states, handling errors, change handlers, etc. Instead, we can spend more time on logic.

 

Material-UI

Formik provides the fields, but it is not the best tool for styling those fields. Material-UI is the solution to that. Material-UI will provide well designed, elegant input fields and structure, which saves us even more time. Check out the syntax for the radio button, checkbox, select, and more on https://material-ui.com/.

 

Yup

Formik has its validation property validate. But as more rules are added, the syntax and lines of code become very long—at times, it even becomes difficult to read. Yup is schema builder which will provide a clean and simple validation object which we will use for validationSchema, which is a Formik property. To have a look at more options for schema, visit https://github.com/jquense/yup.


Let’s get started by installing all the required packages. Here’s the command:

yarn add formik @material-ui yup @types/yup

Once all packages are installed, let’s import all the required components from the packages.

import { Grid, TextField, Button, makeStyles, createStyles, Theme, } from ‘@material-ui/core’
import { Formik, Form, FormikProps } from ‘formik’
import * as Yup from ‘yup’

makeStyles, createStyles, Theme are optional imports. I have used them here for inline styling.

We will be using three properties from Formik, which are initialValues, onSubmit and validationSchema. For demo purposes, I have used a signup form. So under validationSchema we will have some rules, so that our form has all the required fields. onSubmit we will call createUser() to make an API call and reset the form.

As mentioned above, Formik provides validate property, but to reduce complexity we are using Yup. Here’s a little comparison for that.

Comparison between Formik validate and Yup validationSchema

We will use FormikProps to render and bind form fields. This render will define the structure of our form. Though FormikProps have many props we will be using selected ones, like values, touched, errors, handleBlur, handleChange, isSubmitting.

I have created an example code snippet with reference to the signup form and added a mock function createUser that will be triggered upon submission of the form. I’ve also added some additional states to handle form status success or errors.

Without further ado, here’s the complete code for signup form using Formik, Yup, and Material-UI in React-TypeScript.

You can just copy-paste the full code snippet, import the component, and check on the browser. If you are not using TypeScript, you can get rid of interfaces.
Sign up form

Once you run above code snippet, your output should look something like this.

1_kxk4Y_gL453-QZYmw_9lhw

 

Conclusion

With the above approach, we don’t need to worry about handling values, errors, or touched fields. Those are all handled by Formik. The steps we should remember when reusing this form are:

  1. Update the form field’s state in initialValues.
  2. Update inputFields as per requirement.
  3. Update name, id, values, etc. for each input field.
  4. Add the function we want to trigger on form submit.

 

Resources

  1. Formik: https://jaredpalmer.com/formik/docs/overview
  2. Material-UI: https://material-ui.com/
  3. Yup: https://github.com/jquense/yup

That’s it. I hope this is helpful to you. Don’t hesitate to visit the links mentioned above to know more about Formik, Yup, and Material-UI.

Group 212@2x

Interested in a career at Heady?

Excellent! We are always looking for great talent.

app-clips_1
app-clips_2

Interested in a career at Heady?

Excellent! We are always looking for great talent.

LET'S TALK IT OUT.

Figuring out your next step? We're here for you.

Or drop us a line.

hello@heady.io