Formik with yup
Formik with yup

Creating and managing big forms in React is not easy and the complexity of your forms will increased once we start adding custom validations. In this post we are going to learn how to use Formik with yup in React so that boring validation stuff become easy.

Formik

Formik takes care of the repetitive and annoying stuff–keeping track of values/errors/visited fields, orchestrating validation, and handling submission–so you don’t have to. This means you spend less time wiring up state and change handlers and more time focusing on your business logic.

Under the hood formik uses state and props. That means it follows the core pricple of the React instead of rely on fancying things like observers.

It doesn’t rely on 3rd party state management library like Redux/Mobx instead of that it uses React core state management.

Basically Formik do 3 things for you forms.

  1. Management of input values.
  2. Adding validation and showing error messages.
  3. Handling onSubmit functionality.

Installation

npm install formik --save

Example

We are going to use useFormik hook from formik.  It requires an object with initialValues and onSubmit property, and returns an object which has all the helper methods that you need to manage your form state.

const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });

It gonna return a lot of useful functions and values but we required only onSubmit, onChange and values.

import React from 'react';
import { useFormik } from 'formik';

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />
      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />
      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

You can also skip value prop in input element because formik can map values using name prop as well.

Formik with yup

It is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. 

Installation

npm install -S yup

Example:

You can write your validations in object form like this.

const validationSchema = Yup.object({
  firstName: Yup.string().required("Required"),
  lastName: Yup.string().required("Required")
});
import React from "react";
import { useFormik } from "formik";
import * as Yup from "yup";

const validationSchema = Yup.object({
  firstName: Yup.string().required("Required"),
  lastName: Yup.string().required("Required")
});

export default function Register() {
  const { handleSubmit, handleChange, values, errors } = useFormik({
    initialValues: {
      firstName: "",
      lastName: ""
    },
    validationSchema,
    onSubmit(values) {
      console.log(values);
    }
  });
  return (
    <form onSubmit={handleSubmit}>
      <input
        name="firstName"
        onChange={handleChange}
        values={values.firstName}
      />
      {errors.firstName ? errors.firstName : null}
      <input
        name="lastName"
        onChange={handleChange}
        values={values.firstName}
      />
      {errors.lastName ? errors.lastName : null}
      <button type="submit">Submit</button>
    </form>
  );
}
Edit 1mueg

Formik not only works well with hooks but also with render props approach. So if your app doesn’t use hooks, then don’t worry because Formik works without hooks as well.

I hope you have learned how to use Formik with yup in React.

Also checkout top forms libraries.