Search code examples
reactjstailwind-csstailwind-in-js

How to conditionally add/remove classes with TailwindCSS and React


I have an expression that looks for form errors and appends a div if once bubbles up:

{touched && normalizedError && (
      <div className="visible alert-error text-xs text-red-500" role="alert">
        {normalizedError}
      </div>
    )}

I'd like to refactor this and always display the div beneath my input elements but use the invisble class to hide them from the user unless an error is returned—in which case I'd conditional add the visible class.

What's the best way to accomplish this?


Solution

  • There are several ways to accomplish what you want, the easiest would be to add the conditional in the className itself

    <div className={`alert-error text-xs text-red-500 ${touched && normalizedError ? 'visible' : 'invisible'}`}  role="alert">
      {normalizedError}
    </div>