Formik & Yup: A Comprehensive Guide

0
(0)

What is Formik?

Formik is a popular open-source library for building and processing form data in React applications. It simplifies three major challenges developers face while working with HTML forms:

  1. Accessing the proper input values while the form is being submitted at a specific form state.
  2. Validating values entered against each specific form element and generating error messages if any at that very moment.
  3. Handling the submission of the form.

Formik also integrates seamlessly with Yup, a schema-based validation library, providing robust form validation capabilities.

data codes through eyeglasses

Installation

You can install Formik using npm or yarn:

npm i formik --save

or

yarn add formik

Basic Form Handling Without Formik

Here’s how you can handle a basic form using React’s state management:

import React, { useState } from 'react';

function BasicForm() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Input:
        <input type="text" value={inputValue} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default BasicForm;

While the above code is functional, it can become cumbersome to manage forms with multiple inputs and complex validation logic. Formik simplifies these tasks.

Form Handling Using Formik

Formik provides two main ways to handle forms:

  1. Using <Formik>, <Form>, <Field>, and <ErrorMessage> components.
  2. Using the useFormik hook.

Approach 1: Using Formik Components

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

function FormikComponentForm() {
  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      onSubmit={values => {
        console.log(values);
      }}
    >
      {({ handleSubmit }) => (
        <Form onSubmit={handleSubmit}>
          <label>Email:</label>
          <Field type="email" name="email" />
          <ErrorMessage name="email" component="div" />
          <label>Password:</label>
          <Field type="password" name="password" />
          <ErrorMessage name="password" component="div" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  );
}

export default FormikComponentForm;

Example 2: With Validation

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

export default function TestFormik() {
  return (
    <div>
      <Formik
        initialValues={{ email: '', password: '' }}
        validate={values => {
          const errors = {};
          const emailRegExPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
          if (!values.email) {
            errors.email = 'Email Required';
          } else if (!emailRegExPattern.test(values.email)) {
            errors.email = 'Invalid email address';
          }
          if (!values.password) {
            errors.password = 'Password Required';
          }
          return errors;
        }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({ isSubmitting }) => (
          <Form>
            <Field type="email" name="email" placeholder="Email" />
            <ErrorMessage name="email" component="div" />
            <Field type="password" name="password" placeholder="Password" />
            <ErrorMessage name="password" component="div" style={{color:'red'}} />
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}
hand holding react sticker
React JS

Approach 2: Using useFormik Hook

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

function SimpleFormikForm() {
  const formik = useFormik({
    initialValues: {
      email: '',
      password: ''
    },
    onSubmit: values => {
      console.log(values);
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <label>Email:</label>
      <input type="email" name="email" onChange={formik.handleChange} value={formik.values.email} />
      <label>Password:</label>
      <input type="password" name="password" onChange={formik.handleChange} value={formik.values.password} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default SimpleFormikForm;

Validation with Yup

Yup provides schema-based validation for form values. Integrating Yup with Formik allows you to handle form validation easily.

Installation

You can install Yup using npm or yarn:

npm i yup

or 

yarn add yup
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const validationSchema = Yup.object({
  email: Yup.string().email('Invalid email format').required('Required'),
  password: Yup.string().min(8, 'Password must be at least 8 characters').required('Required')
});

export default function YupFormik() {
  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      validationSchema={validationSchema}
      onSubmit={values => {
        console.log('Form data', values);
      }}
    >
      {({ handleSubmit }) => (
        <Form onSubmit={handleSubmit}>
          <label>Email:</label>
          <Field type="email" name="email" /><br />
          <ErrorMessage name="email" component="div" />
          <label>Password:</label>
          <Field type="password" name="password" /><br />
          <ErrorMessage name="password" component="div" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  );
}
man in suit reacting to laptop
Photo by Yan Krukau on Pexels.com

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Comment