DEV Community

Roman
Roman

Posted on • Originally published at programmingly.dev

Mastering Form Handling in React with Formik and Yup

Form handling is an essential part of any web application. It allows you to collect input from users through various forms, such as login, registration, surveys, feedback, and more.

In React, managing forms can quickly become complex, especially as your applications grow. That’s where libraries like Formik and Yup come into play, streamlining the process and reducing boilerplate code.

In this blog post, we’ll explore how to use Formik with Yup to simplify form handling, providing clear, step-by-step instructions and practical examples.

Why Form Handling is Important

Forms are crucial for interacting with users. Whether it’s signing up for an account, submitting feedback, or participating in a survey, forms collect vital data.

A well-designed form enhances user experience and improves data accuracy. However, as forms grow in complexity with multiple fields, validation rules, and submission logic, managing them can become cumbersome.

Common Types of Forms

  1. Login Forms: Used for user authentication, typically requiring a username and password.

  2. Registration Forms: Collects user information to create a new account, including fields like username, email, and password.

  3. Survey Forms: Used to gather feedback or opinions from users.

  4. Contact Forms: Allow users to get in touch with the application’s support team.

React provides state management through hooks in functional components, but as your forms become more complex, managing state and validation can be overwhelming. This is where third-party libraries like Formik and Yup shine.

Popular Form Handling Libraries

In the React ecosystem, two popular libraries for handling forms are:

  • Formik: Simplifies form state management and validation.

  • React Hook Form: Another powerful library that focuses on performance and ease of integration.

In this blog post, we will focus on Formik and its integration with Yup for form validation.

What is Formik?

Formik is a popular library designed to manage forms in React applications. It helps you handle form state, validation, and submission effortlessly. By using Formik, you can concentrate on building your app without getting bogged down by the complexities of form handling. Formik provides a simple way to manage values, errors, and touched states of your inputs.

Getting Started with the useFormik() Hook

The useFormik hook simplifies form management in React. It allows you to manage form state, handle submissions, and validate inputs directly within your functional components. By using useFormik, you can easily access and manipulate form values, handle changes, and manage validation errors.

Basic Example of useFormik

Here’s a simple example of how to use the useFormik hook:

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

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

  return (
    <form onSubmit={formik.handleSubmit}>
      <input
        type="email"
        name="email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <input
        type="password"
        name="password"
        onChange={formik.handleChange}
        value={formik.values.password}
      />
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Why Use the Hook Instead of Formik Components?

While Formik provides several components for building forms quickly, useFormik offers greater flexibility and control over your form’s structure and behavior. Here are some reasons to prefer the hook:

  1. Flexibility: The useFormik hook allows you to use it in any functional component, making it easier to integrate into your existing codebase.

  2. Simplicity: By managing form state and logic directly within your component, you can avoid extra wrapper components, keeping your code cleaner.

  3. Customization: The hook allows for more customization, letting you integrate custom input components or existing libraries without being limited by predefined Formik components.

  4. Performance: Hooks can lead to better performance in some cases, minimizing the number of re-renders compared to higher-order components.

Creating a Registration Form Example with Formik

Let’s create a registration form that includes fields for a username, email, and password. This will illustrate how to handle multiple inputs with Formik.

Registration Form Code

This example shows how to create a registration form in React using Formik.

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

const RegistrationForm = () => {
  const formik = useFormik({
    initialValues: {
      username: '',
      email: '',
      password: '',
    },
    onSubmit: values => {
      console.log('User Registration:', values);
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <input
        type="text"
        name="username"
        placeholder="Username"
        onChange={formik.handleChange}
        value={formik.values.username}
      />
      <input
        type="email"
        name="email"
        placeholder="Email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <input
        type="password"
        name="password"
        placeholder="Password"
        onChange={formik.handleChange}
        value={formik.values.password}
      />
      <button type="submit">Register</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Explanation of the Registration Form

  • Multiple Fields: The form captures three fields: username, email, and password.

  • Controlled Components: Each input is used formik.handleChange to update its corresponding value in the form state.

  • Form Submission: On submission, the values are logged to the console (there we can call API to save our data in DB).

Handling Form with React State vs. Formik

When building forms, you can manage the state using React's built-in state management or utilize Formik. While managing the state manually is feasible, it can lead to excessive boilerplate code and can be less efficient.

Advantages of Using Formik

  • Reduced Boilerplate: Formik handles much of the repetitive code associated with form management, making your components cleaner.

  • Built-in Validation: With Formik, you can easily incorporate validation logic using Yup or custom validation functions.

  • Error Tracking: Formik automatically manages errors and touched states, providing a better user experience.

Handling Forms with React State

If you prefer to manage your form with React state, here’s a simple example:

import React, { useState } from 'react';

const SimpleForm = () => {
  const [email, setEmail] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Email:', email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Handling Forms with Formik

Using Formik simplifies the process significantly. You can manage form state, validation, and submission in one place. Here’s a quick overview:

  • Validation with Yup: Easily validate inputs using Yup.

  • Initial Values: Set up initial values for your form fields.

  • Input Changes: Handle input changes using formik.handleChange.

React Best Practices for Handling Forms

To make your forms more efficient and user-friendly, follow these best practices:

  1. Use Formik for Complex Forms: It reduces boilerplate and handles most form logic for you.

  2. Validate with Yup: Ensure your data is correct before submission.

  3. Keep Components Small: Break down large forms into smaller components for better readability and maintainability.

  4. Error Feedback: Provide clear error messages to guide users in correcting their input.

  5. Use Controlled Components: Maintain form state within React to keep the UI in sync with the data.

Wrapping Up

Mastering form handling in React with Formik and Yup can greatly enhance your development process. These tools simplify the complexities of forms, making your code cleaner and more efficient. By following best practices and using the right libraries, you can create robust forms that improve user experience. Whether you’re building a simple login form or a complex registration process, Formik and Yup provide the necessary tools to handle it seamlessly.

By incorporating these techniques into your React applications, you’ll be well on your way to creating high-quality, user-friendly forms that enhance the overall experience for your users.

This Blog Originally Posted at Programmingly.dev

Please Join our Newsletter for Latest & Trending Web development & Design Articles

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more