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

SoftTimur

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

x00

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>
    }
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related