Categories
React

Make Form Handling Easy in React Apps with Formik

Spread the love

Formik is a library that makes form handling in React apps easy.

In this article, we’ll look at how to handle form inputs with Formik.

Installation

We can install Formik by running:

npm install formik --save

or

yarn add formik

Basic Usage

We can use it by writing:

import React from "react";
import { Formik } from "formik";

export default function App() {
  return (
    <div className="App">
      <Formik
        initialValues={{ email: "", password: "" }}
        validate={(values) => {
          const errors = {};
          if (!values.email) {
            errors.email = "Required";
          } else if (
            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$/i.test(values.email)
          ) {
            errors.email = "Invalid email address";
          }
          return errors;
        }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting
        }) => (
          <form onSubmit={handleSubmit}>
            <input
              type="email"
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}
            <input
              type="password"
              name="password"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            />
            {errors.password && touched.password && errors.password}
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </form>
        )}
      </Formik>
    </div>
  );
}

initialValues has the initial values.

validate is a function that lets us validate form values entered.

values has the values that we entered.

We set the errors object with the errors for the fields.

onSubmit has a function that has the entered values in the values object.

setSubmitting is a function that can we can run to set the form submit state.

In the form element, we set the onSubmit form to the handleSubmit function from the parameter of the render prop to run onSubmit if it’s value.

values.email and values.password have the form value for each field.

handleChange lets us incorporate the entered values into the values object in various places.

onBlur has the handleBlur method to handle blur events.

touched has the touched state for each form field.

isSubmitting has the submitting state of the form.

We can simplify the code with the Form , Field , and ErrorMessage components.

For instance, we can reduce the code above to:

import React from "react";
import { ErrorMessage, Field, Form, Formik } from "formik";

export default function App() {
  return (
    <div className="App">
      <Formik
        initialValues={{ email: "", password: "" }}
        validate={(values) => {
          const errors = {};
          if (!values.email) {
            errors.email = "Required";
          } else if (
            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$/i.test(values.email)
          ) {
            errors.email = "Invalid email address";
          }
          return errors;
        }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({ isSubmitting }) => (
          <Form>
            <Field type="email" name="email" />
            <ErrorMessage name="email" component="div" />
            <Field type="password" name="password" />
            <ErrorMessage name="password" component="div" />
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

The components replace the form input elements and error text.

As long as the name values match between the Field and ErrorMessage , we’ll see the same values displayed.

Conclusion

We can handle forms in React easily with Formik.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *