1
votes

I am using formik library for my react project. I need to disable submit button initially when mandatory fields are empty or have any errors. I checked form status using below code.

const formik = useFormik(false);

        <Formik
        initialValues={!location.state ? InvoiceInitalValues : location.state}
        validationSchema={POValidation} innerRef={formRef}
        onSubmit={(form, actions, formikHelper) => {
          console.log(form);
          console.log(formRef);
          setTimeout(() => {
            saveInvoice(form, actions, formikHelper);
            actions.setSubmitting(false);
          }, 1000);
        }}
      >
        {({
          handleSubmit,
          handleChange,
          setFieldValue,
          values,
          handleReset,
          errors,
          resetForm, isSubmitting


        }) 

I console logged form status using but form is always 'isValid: True'. Please check below image. enter image description here

I printed it in the html also. but always isValid is True. I need to this for disable my button

printed status

 <p> {formik.isValid=== true ? "True" : "False"} </p>

I tried below code to disable my button

<Button className="btn btn-primary mr-1" type="submit" disabled={!formik.isValid}>

Submit

Why formik form validity is always true, even mandatory fields are empty. I spent more time to solve this. still could not fix this. Anyone know to fix this

1

1 Answers

3
votes

You created form using Formik component, but you are checking isValid on another formik instance created through useFormik hook. That's not right.

You should use either <Formik> or useFormik.

As you have written code using Formik component. Here is how you access isValid property:

<Formik
  initialValues={!location.state ? InvoiceInitalValues : location.state}
  // ...
>
  {({
    values,
    handleChange,
    // ... 
    isValid // HERE
  }) => (
    <form onSubmit={handleSubmit}>
      <input
...

Here is a codesandbox.