Mister Babu
Mister Babu

Reputation: 109

Tailwind CSS transition on load

I am trying to add an opacity transition on a div. It should start at opacity 0 and once it is visible on the screen it should fade in slowly, to the maximum opacity.

Here is my code:

<div className="transition-opacity ease-in-out opacity-0 <STATE>:opacity-100 duration-300"> ... </div>

However, I do not know what state to use for my purpose. What should I replace the STATE from above with? Or is it not the right approach?

Upvotes: 1

Views: 12501

Answers (3)

Anastasiya Stanevich
Anastasiya Stanevich

Reputation: 326

You can define animation which will be envoked right after component will be rendered.

To define custom animation in tailwind:

  • go to tailwind.config.js
  • add new animation:
module.exports = {
   ...,
   theme: {
     ...,
     extend: {
       ...,
       keyframes: {
         appear: {
           "0%": {
             opacity: "0",
           },
           "100%": {
             opacity: "1",
           },
        },
        animation: {
          appear: "appear 0.5s ease-in-out",
        }
     }
}
  • in your file use your animation in tailwind way:
<div className="animate-appear" />

Upvotes: 4

Rian
Rian

Reputation: 11

try adding this

<div className="duration-75">
...

Upvotes: -1

Alex Stringer
Alex Stringer

Reputation: 56

Think you are on the right track with this, you'd just need to toggle a class upon load:

const [loaded, setLoaded] = useState(false);

handleLoad = () => {
  setLoaded(true);
}

componentDidMount() {
  window.addEventListener('load', this.handleLoad);
}

<div className={`${loaded ? "opacity-100" : "opacity-0"}`>

If there's a more elegant solution to this from a React expert, would be good to know :)

Upvotes: 3

Related Questions