Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty error div from DOM in formik form?

Tags:

reactjs

formik

I have the following code in the authentication page to control alert messages:

<div className="messages-wrapper">
  {formik.errors.email &&
    <div className="alert alert-danger">
      <ErrorMessage name="email" />
    </div>
  }
  {formik.errors.password &&
    <div className="alert alert-danger">
      <ErrorMessage name="password" />
    </div>
  }
  {error && <div className="alert alert-danger">{error}</div>}
</div>

I realize that sometimes in DOM it has:

<div class="alert alert-danger"></div>

As a consequence, there is a pink bar in the display.

Does anyone know how to implement such that we only display an alert bar when it has text?

enter image description here

like image 445
SoftTimur Avatar asked Dec 01 '25 03:12

SoftTimur


1 Answers

The code sample you've provided is not enough to give you a definitive answer.

But from what I see I can figure this much:

  1. As per documentation 1 and 2 and the source code the <ErrorMessage name="email"> will returns a string, and you code is roughly equivalent to
    {formik.errors.email && <div className="alert alert-danger">
      {formik.touched.email && formik.errors.email ? formik.errors.email : null}
    </div>}
    
  2. Now I see two possibilities for an empty error bar to appear:

    1. formik.errors.email must be truthy, but not printable (like for example " ").
    2. formik.errors.email must be truthy, and formik.touched.email must be falsy.

    Most probably it's the second issue you're experiencing.

So, if I guessed right, you need to either:

  1. Use ErrorMessage as it is recommended in the docs. Like so:
    <ErrorMessage name="email">
      {msg => <div className="alert alert-danger">{msg}</div>}
    </ErrorMessage>
    
    Or like so:
    <ErrorMessage
      name="email"
      render={msg => <div className="alert alert-danger">{msg}</div>}
    />
    
  2. Or get rid of <ErrorMessage>, but add a check for the touched
    {formik.touched.email && formik.errors.email &&
      <div className="alert alert-danger">{formik.errors.email}</div>
    }
    
like image 120
x00 Avatar answered Dec 04 '25 13:12

x00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!