0

Is there any way to create a display or visibility transition using Tailwind and a conditional code at Next? I'm trying something like this, what I would like to achieve is a smooth fade in effect when the backend returns a exception message under the responseError object (using Context in Next) but there's no transition effect at all:

{
  responseError ?
    <span className={`${ responseError ? "visible transition-all ease-in-out delay-150 duration-300" : "invisible"} pt-4 text-sm text-red-500 font-['Poppins'] font-bold `}>
       username or password incorrect
     </span>
  : null
 }

or

{
  responseError ?
    <span className={`${ responseError ? "visible transition-all ease-in-out delay-150 duration-300" : "invisible"} pt-4 text-sm text-red-500 font-['Poppins'] font-bold `}>
       { responseError.message }
    </span>
  : null
}

1 Answers1

3

Use opacity instead of visibility.

This stack overflow answer goes over a similar issue you are facing. In short, the visibility property has two possible values: visible or hidden. On the other hand, opacity can be between 0 and 1, so proper keyframes can be applied when using the transition property.

As a side note, I noticed you are checking for the responseError twice, once to render the <span> and again to apply tailwind classes. This will cause your fade in transition to only work when fading in because the <span> is only rendered when responseError exists. Instead, try something like this:

<span className={`${ responseError ? "opacity-100" : "opacity-0"} transition-opacity ease-in-out delay-150 duration-300 pt-4 text-sm text-red-500 font-['Poppins'] font-bold `}>
   { responseError ? responseError.message : '' }
</span>
Rico Hancock
  • 366
  • 6
  • 1
    This is a good answer, thought I would add, the opacity-0 element is still going to get in the way on your layout, whereas the hidden class gives you that space back as it's display:none. That means if you want to use opacity-0 to 100 transitions for slideshows and the likes, you will have to use absolute positioning to overlay anything and handle any widths/heights some other way. – John Lewis May 09 '23 at 16:00