0

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?

Ken Prince
  • 1,437
  • 1
  • 20
  • 26
  • 1
    Does this answer your question? [React Js conditionally applying class attributes](https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes) – Konrad Jan 16 '23 at 22:50
  • 3
    [`clsx`](https://www.npmjs.com/package/clsx) – Konrad Jan 16 '23 at 22:51

2 Answers2

4

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>

ludwiguer
  • 2,177
  • 2
  • 15
  • 21
1

There are many different ways of getting this done.

1.Inline inside the class

<div className={`... ${touched && normalizedError ? 'visible' : 'invisible'}`}>
  {normalizedError}
</div>

2. Using a variable

let dependentClass = touched && normalizedError ? 'visible' : 'invisible';

className={`... ${dependentClass }`}

3. Using clsx

<div className={clsx('...',`${touched && normalizedError ? 'visible' : 'invisible'}`)}>
  {normalizedError}
</div>
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88