Home > Blockchain >  TailwindCSS animations on conditionally rendered components in React
TailwindCSS animations on conditionally rendered components in React

Time:11-08

If I am conditionally rendering a component depending on some state, how can I animate its transition between its open and closed states in React with TailwindCSS?

{successMessage && (
              <div className="flex transition-all ease-in-out duration-300 bg-gray-200 w-44 items-center justify-between px-2 rounded">
                <p>Added to watchlist!</p>
                <button onClick={() => setSuccessMessage(false)}>X</button>
              </div>
            )}

This code half works but there is no animation or transition period to it. How can I fix this?

CodePudding user response:

I would recommend AOS libary to do this, as you would need to do some more work to make this work with TailwindCSS.

Try this

Install Aos

npm install aos --save

Put in your file

import React, { useEffect } from "react";
import AOS from 'aos';
import "aos/dist/aos.css";

useEffect(() => {
  AOS.init({
    duration : 1000
  });
}, []);

You can change duration as you like.

Add as attribute to HTML tag
data-aos="animation_name"

Example

 <div> data-aos="fadeIn" </div>

Extra Attributes you can use

    data-aos="fade-up"
    data-aos-offset="200"
    data-aos-delay="50"
    data-aos-duration="1000"
    data-aos-easing="ease-in-out"
    data-aos-mirror="true"
    data-aos-once="false"
    data-aos-anchor-placement="top-center"

List of all animation

Documentation

CodePudding user response:

Try something like this :

  <div className={`flex transition-all ease-in-out duration-300 bg-gray-200 w-44 items-center justify-between px-2 rounded ${your_state ? 'opacity-100' : 'opacity-0'}`}>
   ...
  </div>
  • Related