Build Forms Easily in React with Formik

Share with a friend:

Forms are an integral part of many web applications, allowing users to input and submit data. In React, managing form state and validation can be a complex task. That’s where Formik comes in. Formik is a popular form library for React that simplifies the process of building and managing forms. In this tutorial, we will explore how to build forms with Formik in React and leverage its powerful features.

Table of Contents

What is Formik?

Formik is a form library for React that aims to make handling forms more manageable and less verbose. It provides a set of utilities and components that help with form state management, input validation, error handling, and form submission. With Formik, you can streamline the process of building forms in your React applications and ensure a great user experience.

Installation

To get started with Formik, you need to have a React project set up. If you don’t have one, you can create a new React application using Create React App or any other boilerplate. Once you have your project ready, you can install Formik by running the following command:

npm install formik

or if you prefer Yarn:

yarn add formik

Building a Simple Form

Let’s start by building a simple form using Formik. We’ll create a basic registration form with fields for name, email, and password. First, import the necessary components from Formik:

import { Formik, Field, ErrorMessage } from 'formik';

Next, define a functional component that renders the form:

const RegistrationForm = () => {
  return (
    <Formik
      initialValues={{ name: '', email: '', password: '' }}
      onSubmit={values => {
        console.log(values);
      }}
    >
      {({ handleSubmit }) => (
        <form onSubmit={handleSubmit}>
          <div>
            <label htmlFor="name">Name</label>
            <Field type="text" id="name" name="name" />
            <ErrorMessage name="name" component="div" />
          </div>
          <div>
            <label htmlFor="email">Email</label>
            <Field type="email" id="email" name="email" />
            <ErrorMessage name="email" component="div" />
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <Field type="password" id="password" name="password" />
            <ErrorMessage name="password" component="div" />
          </div>
          <button type="submit">Submit</button>
        </form>
      )}
    </Formik>
  );
};

In the above code, we wrap the form with the Formik component and provide the initial values for the form fields using the initialValues prop. We also define the onSubmit callback, which will be called when the form is submitted.

Inside the Formik component, we pass a function as a child. This function receives an object with several useful properties and methods. In this example, we’re using the handleSubmit method, which is responsible for handling form submission.

For each input field, we use the Field component from Formik, specifying the input type, id, and name. We also include an ErrorMessage component, which displays any validation errors associated with the field.

Finally, we have a submit button that triggers the form submission.

Handling Form Validation

Form validation is an essential aspect of building forms. With Formik, you can easily add validation rules to your form fields. Let’s enhance our registration form by adding validation for the name, email, and password fields.

To define validation rules, we’ll create a validation function outside the RegistrationForm component:

const validate = values => {
  const errors = {};

  if (!values.name) {
    errors.name = 'Name is required';
  }

  if (!values.email) {
    errors.email = 'Email is required';
  } else if (!/\S+@\S+\.\S+/.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  if (!values.password) {
    errors.password = 'Password is required';
  } else if (values.password.length < 8) {
    errors.password = 'Password must be at least 8 characters long';
  }

  return errors;
};

In this example, we define a validate function that takes the form values as input and returns an object with error messages for each invalid field. We check if the name, email, and password fields are empty and add corresponding error messages. For the email field, we also use a regular expression to validate the email format. Finally, we check if the password is at least 8 characters long.

To use the validation function in our form, we pass it as a prop to the Formik component:

<Formik
  initialValues={{ name: '', email: '', password: '' }}
  validate={validate}
  onSubmit={values => {
    console.log(values);
  }}
>
  {/* ... */}
</Formik>

By providing the validate prop, Formik will automatically run the validation function on each form submission or field change. If there are any validation errors, they will be displayed by the ErrorMessage components.

Handling Form Submission

After validating the form, we need to handle the form submission. In our example, we’re currently logging the form values to the console. However, in a real application, you would typically send the form data to a server or perform any other necessary actions.

To handle the form submission, we can update the onSubmit callback in the Formik component:

onSubmit={async (values, { setSubmitting }) => {
  // Perform API call or any other async action
  await submitForm(values);

  setSubmitting(false);
}}

In this updated onSubmit callback, we use the async/await syntax to handle asynchronous operations. Inside the callback, you can perform any necessary actions, such as making an API call to submit the form data. We also use the setSubmitting function to indicate that the submission is complete.

Additional Formik Features

Formik offers many other powerful features to enhance your form-building experience:

  • Form Reset: Formik provides a handleReset function that allows you to easily reset the form to its initial state.
  • Form Field Reusability: You can create reusable form field components using Formik’s Field component. This makes it convenient to maintain consistent styling and behavior across different forms in your application.
  • Formik Context: With Formik’s useFormikContext hook, you can access the Formik context outside of the Formik component. This can be useful when you need to access form values or perform actions based on form state outside of the form itself.
  • Formik with Yup: Formik integrates well with Yup, a JavaScript schema builder for value parsing and validation. You can use Yup to define validation schemas and easily apply them to your Formik forms.

These are just a few highlights of what Formik has to offer. The library is highly customizable and provides extensive documentation to help you with your form-building needs.

Conclusion

Building forms in React can be complex, but with Formik, the process becomes more manageable and less error-prone. In this tutorial, we explored how to build forms with Formik in React. We learned how to create a simple form, add form validation, and handle form submission. Additionally, we briefly touched on some of the advanced features Formik provides.

Share with a friend:

Rajae Robinson

Rajae Robinson is a young Software Developer with over 3 years of work experience building websites and mobile apps. He has extensive experience with React.js and Next.js.

Recent Posts