How to Disable the Submit Button in Formik

By Saheb Sutradhar - Updated On 15-03-2024

How to Disable the Submit Button in Formik

Form submissions are a crucial part of web development, allowing users to interact with and provide data to applications. However, there are instances where you might want to disable the submit button, perhaps while data validation is in progress or when certain conditions are not met. If you're using Formik, a popular form library for React, disabling the submit button can be achieved efficiently.

In this guide, we'll walk through the steps of How to disable the submit button in Formik.

1. Disabling the Button when the form is in the process of submission

Step 1

Install Formik If you haven't already installed Formik in your React project, you can do so using npm or yarn. Open your terminal and run the following commands.

npm install formik

Step 2

Set up Your Form with Formik Assuming you have a basic understanding of Formik, let's create a simple form component using Formik. Start by importing the necessary modules.

import React from 'react';
import { Formik, Form, Field } from 'formik';

Now, create your form component.

const MyForm = () => (
  <Formik
    initialValues={{
      // Define your form fields here
    }}
    onSubmit={(values, actions) => {
      // Handle form submission logic
    }}
  >
    {({ isSubmitting }) => (
      <Form>
        <Field type="text" name="firstName" />
        <Field type="text" name="lastName" />
        <button type="submit" disabled={isSubmitting}>
          Submit
        </button>
      </Form>
    )}
  </Formik>
);

Step 3

Disable the Submit Button In the above code snippet, notice how we've used the isSubmitting prop provided by Formik to disable the submit button conditionally. When the form is in the process of submission, isSubmitting will be true, and the button will be disabled automatically.

Step 4

Custom Conditions for Disabling You can also implement custom conditions for disabling the submit button. For example, you might want to disable the button until certain fields are filled or until specific validation criteria are met. You can achieve this by maintaining your state and conditionally setting the disabled attribute of the button.

<Formik
  initialValues={{
    // Define your form fields here
  }}
  onSubmit={(values, actions) => {
    // Handle form submission logic
  }}
>
  {({ isSubmitting, values }) => (
    <Form>
      <Field type="text" name="firstName" />
      <Field type="text" name="lastName" />
      <button type="submit" disabled={!values.firstName || !values.lastName || isSubmitting}>
        Submit
      </button>
    </Form>
  )}
</Formik>

In this example, the submit button will be disabled if either the firstName or lastName field is empty, or if the form is in the process of submitting.

2. Disabling the Button Initially

When the form loads, to keep the submit button disabled, you can use the dirty property of Formik. The dirty property indicates whether any form field values have changed from their initial state. Here’s how you can do it.

import { useFormik } from "formik";
import * as Yup from "yup";

const formik = useFormik({
  initialValues: {
    firstName: "",
    lastName: "",
    email: "",
  },
  validationSchema: Yup.object({
    firstName: Yup.string()
      .max(15, "Must be 15 characters or less")
      .min(3, "Must be at least 3 characters")
      .required("Required"),
    lastName: Yup.string()
      .min(3, "Must be at least 3 characters")
      .max(20, "Must be 20 characters or less")
      .required("Required"),
    email: Yup.string()
      .email("Invalid email address")
      .required("Required"),
  }),
  onSubmit: (values) => {
    // Handle form submission
  },
});

// In your JSX:
<button type="submit" disabled={!formik.dirty}>
  Submit
</button>

The disabled={!formik.dirty} expression ensures that the submit button remains disabled until the user interacts with the form fields.

3. Disabling the Button Based on Validity

If you want the submit button to be disabled until all field values are valid, you can use the isValid property. This property returns true if there are no validation errors and false otherwise.

<button type="submit" disabled={!formik.isValid}>
  Submit
</button>

4. Combining Both Conditions

To disable the button until all fields are valid and have been changed from their initial values, use both isValid and dirty together.

<button type="submit" disabled={!(formik.isValid && formik.dirty)}>
  Submit
</button>

This ensures that the button remains disabled until all validations pass and the user interacts with the form.

Conclusion

Disabling the submit button in Formik is a straightforward process that can be achieved using the isSubmitting prop provided by Formik. By following the steps outlined in this guide, you can ensure that your forms provide a smooth user experience, especially during form submission and validation processes. Whether you need to disable the button temporarily or based on custom conditions, Formik offers the flexibility to meet your requirements effectively.

codelearningpoint © 2024