Formik

Posted July 24, 2023 by Rohith and Anusha ‐ 4 min read

Developing forms in React applications can be a complex and time-consuming task. Handling form validations, managing form state, and synchronizing form data with the application's state can quickly become overwhelming. Enter Formik, a powerful and popular library that simplifies form management in React projects.

What is Formik?

  • Formik is an open-source library for managing forms in React applications.

  • Created by Jared Palmer, it provides a set of utilities and components that make building and maintaining forms much more straightforward and less error-prone.

  • Formik is widely adopted within the React community due to its simplicity, flexibility, and robustness.

Key Features of Formik

Form State Management

  • Formik centralizes form state management, keeping track of form values, touched fields, errors, and more.

  • It ensures that form state remains in sync with the input elements, reducing the need for manual handling of form data.

Form Validation

  • Validating user input is a crucial aspect of form development.

  • Formik simplifies form validation by allowing you to define validation rules as functions or using popular validation libraries like Yup.

  • It automatically handles error messages and displays them to users, making the validation process seamless.

Form Submission

  • Formik streamlines the process of handling form submissions.

  • By providing a straightforward onSubmit prop to the <Formik> component, developers can define the logic that executes when the form is submitted successfully.

  • Formik takes care of the form data and handles form submission events.

Field-Level Validation

  • Formik allows you to implement field-level validation, meaning you can define specific validation rules for individual form fields.

  • This granular control is especially helpful when you need different validation criteria for different parts of the form.

Form Reset and Initialization

  • `Resetting a form to its initial state is often necessary after a submission or when canceling an operation

  • Formik makes it effortless to reset the form to its initial values and touched state.

Handling Form Events

  • Formik provides an easy way to handle common form events, such as onBlur and onChange, ensuring that form state is updated accordingly.

  • This feature is vital for displaying real-time validation errors or other UI changes based on user input.

How to Use Formik

Using Formik in your React application is a straightforward process. Here are the steps to get started:

Installation

To use Formik, you first need to install it as a dependency in your project. You can do this using npm or yarn:

npm install formik
# or
yarn add formik

Import and Wrap Your Form

After installing Formik, import it into your component and wrap your form with the <Formik> component. Pass the initial form values, validation schema (optional), and an onSubmit function as props:

import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

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

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

const onSubmit = (values, { setSubmitting }) => {
  // Handle form submission logic here
  console.log(values);
  setSubmitting(false);
};

const MyForm = () => {
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
    >
      <Form>{/* Form fields go here */}</Form>
    </Formik>
  );
};

export default MyForm;

Create Form Fields

Within the <Form> component, you can create form fields using the <Field> component and handle their events and validation with ease:

<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />

<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />

<Field as="textarea" name="message" />
<ErrorMessage name="message" component="div" />

Handle Form Submission

  • Upon successful form submission, the onSubmit function defined earlier will be triggered.

  • This is where you can handle the form data, make API calls, or update the application state accordingly.

Conclusion

  • Formik is an invaluable tool for managing forms in React applications.

  • It simplifies form development, streamlines form state management, and provides an elegant way to handle form validation and submission.

  • With its intuitive API and extensive documentation, Formik empowers developers to create robust, user-friendly forms with ease.

  • If you’re building React applications that rely on complex forms, Formik is undoubtedly worth incorporating into your project.

quick-references blog react react-library formik form-management

Subscribe For More Content