Plainsurf Solutions

Master Form Handling in React Application with Formik and Yup

handle-form-data-with-formik-and-yup

Handling forms in React applications can be a challenging task, especially when it comes to validating user input and managing form submission. Fortunately, there are powerful libraries like Formik and Yup that simplify the process and offer a robust solution for managing form state, validation, and submission. In this blog, we will explore how to leverage Formik and Yup to create a seamless and efficient form handling experience in React.

Table of Contents:

  • What is Formik?
  • What is Yup?
  • Setting Up a React Project
  • Installing Formik and Yup
  • Creating a Basic Form
  • Handling Form Submission
  • Form Validation with Yup
  • Displaying Validation Errors
  • Form Reset and Initialization
  • Advanced Form Features
  • Formik with Third-Party Components
  • Conclusion

What is Formik?

Formik is a popular React library that simplifies form management by abstracting away the complexities of handling form state, validation, and submission. It provides a straightforward API and allows developers to easily integrate forms into their applications.

What is Yup?

Yup is a JavaScript schema validation library that works seamlessly with Formik. It enables developers to define validation rules and schemas to ensure that the data submitted through the form meets specific criteria.

Setting Up a React Project

Before we dive into Formik and Yup, let’s set up a new React project. Open your terminal or command prompt and run the following command to create a new React project using Create React App:

npx create-react-app my-react-form-app

Replace “my-react-form-app” with the desired name of your project. You can setup your project using Create React App or your preferred method. Refer our blog on Create React App to learn more.

Installing Formik and Yup

We’ll start by installing Formik and Yup in our project using npm or yarn. To install Formik and Yup, run the following command in your terminal:

npm install formik yup

This command will use npm (Node Package Manager) to install the latest versions of Formik and Yup and add them as dependencies to your project’s package.json file.

Creating a Basic Form

Now that you have Formik and Yup installed in your React project, it’s time to create a basic form using Formik. In this section, we’ll walk through the steps to build a simple form with a few input fields and understand the core components provided by Formik to manage form state.

Set Up Formik Component

In your React component file where you want to create the form, import the necessary dependencies:

import React from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';

Define Initial Form Values

Before creating the form, define the initial values for your form fields. This is usually done as an object with key-value pairs representing the field names and their initial values.

const initialValues = {
  name: '',
  email: '',
  message: '',
};

Define Form Validation Schema with Yup

To add form validation to your form, create a Yup schema that defines the validation rules for each field. Yup provides a simple and intuitive API to set up validation.

const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
  message: Yup.string().required('Message is required'),
});

Create the Form Component

Now, it’s time to create the actual form component using Formik. Within your functional component, wrap the form content with the <Formik> component, passing in the initialValues, validationSchema, and the onSubmit function as props.

const MyForm = () => {
  const handleSubmit = (values, { setSubmitting }) => {
    // Handle form submission logic here
    console.log(values);
    setSubmitting(false);
  };
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {({ values, handleChange, handleSubmit, isSubmitting }) => (
        <form onSubmit={handleSubmit}>
          {/* Form fields */}
          <div>
            <label htmlFor="name">Name:</label>
            <input
              type="text"
              id="name"
              name="name"
              value={values.name}
              onChange={handleChange}
            />
          </div>
          <div>
            <label htmlFor="email">Email:</label>
            <input
              type="email"
              id="email"
              name="email"
              value={values.email}
              onChange={handleChange}
            />
          </div>
          <div>
            <label htmlFor="message">Message:</label>
            <textarea
              id="message"
              name="message"
              value={values.message}
              onChange={handleChange}
            />
          </div>
          {/* Submit button */}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  );
};

Handle Form Submission

In the example above, the handleSubmit function is responsible for handling the form submission logic. Customize this function to suit your specific needs, such as sending form data to a server, updating state, or performing any other actions you require.

Form Reset and Initialization

Formik provides a handy resetForm function that you can use to reset the form to its initial state. You can call this function whenever you need to clear the form after submission or any other specific event.

const handleFormReset = (resetForm) => {
  // Call the resetForm function to reset the form
  resetForm();
};

In your form component, pass the resetForm function to the handler (e.g., onClick of a reset button):

{/* Reset button */}
          <button type="button" onClick={() => handleFormReset(resetForm)}>
            Reset
          </button>

To initialize the form with default or saved values, you can pass the initialValues prop with the desired values when rendering the Formik component. For example, you can use data from an API response or local storage to populate the form.

const savedValues = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  message: 'Hello, Formik!',
};

And replace  initialValues={initialValues} with 

initialValues={savedValues} // Pass the saved values here

These initial values can be retrieved from an API or local storage.

Advanced Form Features

Advanced Form Features in Formik refer to additional functionalities and techniques that can further enhance the form handling experience and provide more control and customization to the developers. These features include handling arrays of form fields, working with custom input components, conditional form fields, and leveraging Formik’s utility functions.

Formik with Third-Party Components

sing Formik with third-party components is a common practice in React applications. Formik provides an easy and flexible way to integrate third-party UI libraries and custom input components with its form state management.

Conclusion

Formik and Yup are powerful tools that significantly simplify form handling in React applications. They streamline the process of managing form state, validating user input, and handling form submissions, ultimately improving the overall user experience. By mastering Formik and Yup, developers can build robust, user-friendly forms that meet the needs of their React projects with ease.

Published
Categorized as React