Simplify Form Handling with Yup and Formik in React
Tags: coding, formik, react, formhandling
Published: 2023-09-26 16:19:49

Forms are a fundamental part of web applications, and handling them effectively can make or break the user experience. In React, managing forms can be complex, especially when you need to perform client-side validation and submit data to a server. Fortunately, libraries like Yup and Formik come to the rescue, making form management more straightforward, organized, and less error-prone. Let's explore why Yup and Formik are beneficial and walk through an example of how to use them to create a dynamic form in a React application. 

---
But first....

<h2>What is Form Handling?</h2>
Form handling in web development encompasses several essential tasks that ensure a smooth user experience:

**User Interaction:** Capturing and processing user input through form elements like text fields, checkboxes, and dropdowns.

**Form State Management:** Managing the state of form components, including tracking user input and reflecting changes.

**Validation:** Ensuring the correctness of user-submitted data by validating it against predefined rules.

**Error Handling:** Providing feedback to users when validation fails or other errors occur during submission.

**Submission:** Sending user data to a server for further processing, often involving HTTP requests or backend interactions.

**Feedback and Confirmation**: Confirming to users that their data was received and processed successfully.

**Resetting or Clearing:** Offering options to reset or clear the form for a better user experience.

Form handling in React applications combines libraries like Yup and Formik to streamline and simplify these tasks, resulting in efficient and user-friendly forms.

---
<h2>Why Yup and Formik?</h2>
Let's understand why Yup and Formik are a great combination for handling forms in React:

<h3>1. Validation with Yup</h3>
Yup is a powerful and flexible JavaScript schema validation library. It allows you to define schemas for your form data and validate it easily. Some key benefits of using Yup for validation are:

**Declarative Schema Definition:** You can define your data schema in a declarative way using JavaScript objects, making it easy to understand and maintain.

**Server and Client-Side Validation:** Yup supports both server-side and client-side validation, ensuring consistent data validation across your application.

**Custom Validation Rules:** You can create custom validation rules and error messages, giving you full control over how your form data is validated.

<h3>2. Form Management with Formik</h3>
Formik is a library that simplifies the process of building and managing forms in React. It provides a set of utilities and components that streamline form creation and validation. Formik benefits include:

**Form State Management:** Formik handles the state of your form components, reducing boilerplate code for controlled components and form state management.

**Validation Integration:** Formik integrates seamlessly with validation libraries like Yup, making it easy to validate form data with error messages displayed to users.

**Submission Handling:** Formik simplifies form submission and error handling, making it easy to interact with APIs or perform other actions when the form is submitted.

---
To get started, make sure you install yup and Formik and correctly import them to be able to use in your code.

In my BookHub app, I created a form where a user can upload a book with a title, author, description, image, genre, and status of "read" or "want to read." This component is called "AddBookForm."
First, we define a Yup schema (formSchema) that specifies validation rules for the form fields. In this example, both the "title" and "author" fields are required.

```
const formSchema = yup.object().shape({
      title: yup.string().required("Must enter a title"),
      author: yup.string().required("Must enter an author"),
    })
```
Inside the AddBookForm function, we initialize Formik by calling useFormik. We provide initial form values, the validation schema, and an onSubmit function that handles form submission:

```
const formik = useFormik({
      initialValues: {
        title: '',
        author:'',
        description: '',
        image: '',
        genre: '',
        status: 'want-to-read'
      },
      validationSchema: formSchema,
      onSubmit: (values) => {
        fetch('/books', {
          method:"POST",
          headers: {
            "Content-Type" : "application/json",
          },
          body: JSON.stringify(values)
        }).then((res) => {
          if(res.ok) {
            res.json().then(book => {
              addBook(book)
              navigate(`/books/${book.id}`)
            })
          }
        })
      }
    })
```
Within the return statement, we create the form elements using standard HTML input elements for each field, including "title" and "author." 
For each input field, we connect the value, name, and onChange properties to Formik's state and handlers, ensuring that the form state is controlled by Formik.

```
return (
      <div className="add-box">
        <h2>Add Book</h2>
        <form onSubmit={formik.handleSubmit}>
          <div className="user-box">
            <input
              type="text"
              name="title"
              value={formik.values.title}
              required
              onChange={formik.handleChange}
            />
            <label>Title</label>
          </div>
//Do this for each input field
```
---
With Yup handling schema validation and Formik managing the form state and submission, this dynamic form becomes more manageable and less error-prone. The separation of concerns between form state and validation logic leads to cleaner and more maintainable code.

When working with forms in React, especially complex ones, using libraries like Yup and Formik can significantly simplify the development process. Yup ensures data integrity and validation, while Formik handles form state and submission, resulting in a more organized and efficient codebase.