DEV Community

Harpreet Singh
Harpreet Singh

Posted on

Easy Forms with Formik and Yup

Form handling is a fundamental aspect of web development, allowing users to interact with applications by providing input. Managing form state, validation, and submission in React can be complex, but with the help of libraries like Formik and Yup, this process becomes streamlined and efficient. In this blog post, we'll explore how Formik simplifies form management in React applications, and how Yup complements it by providing robust schema validation making our lives easier.

Features

  • Simple and Intuitive API
    Formik's API is clean and intuitive, making it easy to manage forms in React applications. It encapsulates the form's state and provides methods to handle form submission, validation, and more.

  • Built-in Validation
    Formik includes built-in support for form validation. It allows you to define validation rules for each field, providing immediate feedback to users on invalid inputs.

  • Form State Management
    Formik takes care of managing the form state, including values, touched fields, and form submission status. This eliminates the need for manual state management, reducing boilerplate code.

  • Error Handling
    Formik provides an elegant way to manage and display form errors. It keeps track of the validation status of each field and makes it easy to display error messages.

Installation

Let's begin with installing Formik and Yup

npm install formik yup
Enter fullscreen mode Exit fullscreen mode

Imports

Now we can import Formik and Yup in our react form component

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

Initial Values

Formik requires that we give it initial values to start with. Here's an example:

const initialValues = {
  name: '',
  email: '',
};
Enter fullscreen mode Exit fullscreen mode

Validation Schema

Formik also requires we provide a validation schema. Here is where we use the validation prowess of Yup

const validationSchema = Yup.object({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email address').required('Email is required'),
});
Enter fullscreen mode Exit fullscreen mode

onSubmit

Formik provides a onSubmit by default when you submit your form. You can customize this with any logic you need such as for a POST request to your api. In this example, let's just console log the values

const onSubmit = (values) => {
  console.log(values);
Enter fullscreen mode Exit fullscreen mode

Formik Input Form

Now that we've set the three requirements by Formik {initialValues, validationSchema, onSubmit}, let's create our form to accept input

const App = () => {
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
    >
      <Form>
        <div>
          <label htmlFor="name">Name:</label>
          <Field type="text" id="name" name="name" />
          <ErrorMessage name="name" component="div" className="error" />
        </div>

        <div>
          <label htmlFor="email">Email:</label>
          <Field type="email" id="email" name="email" />
          <ErrorMessage name="email" component="div" className="error" />
        </div>

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Notice the tags which make displaying error messages super simple and automated by Formik and Yup based on the validation schema.

Conclusion

Formik and Yup are powerful tools that greatly simplify form management and validation in React applications. By leveraging the intuitive API of Formik and the robust validation capabilities of Yup, developers can create interactive and user-friendly forms with ease. As shown in the examples, Formik and Yup provide the necessary tools to get the job done efficiently and effectively. Start incorporating them into your React projects and experience the benefits firsthand!

Here's more information

Formik Docs

Top comments (0)