Must-Know React Libraries - Formik and Yup

What are Formik and Yup?

What is Formik?

Formik is a library that simplifies the management of form components. It is used to manage user inputs, error messages, and the overall form state (e.g., whether it has been submitted or is valid). Formik automatically tracks and controls the form's state and validity.

What is Yup?

Yup is a schema validation library for JavaScript. When used with Formik, it can be used to validate user inputs. With Yup, you can define which fields are required, how to validate certain formats, and more.

Simple Example

Below, we will create a simple form using Formik and Yup. The form will have an email and a password field, and these fields will be subject to validation rules.

Installing the Required Packages

npm install formik yup

Example Code


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

const MyForm = () => {
  const validationSchema = Yup.object().shape({
    email: Yup.string()
      .email('Invalid email address')
      .required('Email is required'),
    password: Yup.string()
      .min(6, 'Password must be at least 6 characters')
      .required('Password is required'),
  });

  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      validationSchema={validationSchema}
      onSubmit={(values) => {
        console.log('Form values:', values);
      }}
    >
      {() => (
        <Form>
          <div>
            <label htmlFor="email">Email:</label>
            <Field name="email" type="email" />
            <ErrorMessage name="email" component="div" />
          </div>

          <div>
            <label htmlFor="password">Password:</label>
            <Field name="password" type="password" />
            <ErrorMessage name="password" component="div" />
          </div>

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
};

export default MyForm;

Explanation

  1. Importing Formik and Yup: We import the Formik and Yup libraries.
  2. Validation Schema: We define a validationSchema using Yup. For the email field, we specify a valid email format, and for the password field, we require a minimum of 6 characters.
  3. Using Formik: We create the form using the Formik component. The initialValues prop is used to define the initial values of the form fields.
  4. Field and ErrorMessage: We define the form fields and error messages. The Field component represents the form fields, while the ErrorMessage component is used to display validation error messages.
  5. Submit Handler: When the form is submitted, the onSubmit function is triggered and logs the form values to the console.

This example demonstrates the basics of creating a simple form using Formik and Yup. You can add more fields and extend the validation rules to suit your needs.

Comments