skip to Main Content

I am wondering how can I trigger css animation when state updated in react js.
I am using 1 div to render the data dynamically in the case while the css animation will only be triggered once.
Do we have any solution for that?

Simplified code:

const [data, setData] = useState(0);

return(
  <>
    <div className="fade-in">
     <p>{data}</p> // this data will change by some event, I want the css animation to be triggered every time when data changes
    </div>
  </>
)

css

.fade-in{
  animation: fadein 1100ms;
}

@keyframes fadein {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

I don’t really want to make multiple divs to display data and to make 1 of them active to trigger css driven by event because I want to make the component simple and dynamic.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you guys for your help!
    But I think I may have found the easiest way to do it on my own.
    Turns out we can update the key of the root component to tell react that this is a totally different component so it will re-render the component.
    By which, the css will be triggered again as the entire component has been newly rendered!
    The code-wise effort is smallest so I will just go with this approach!

    e.g.

      const [data, setData] = useState(0);
    
      const handleOnChange = () => {
        setDate(Math.random());
      }
    
      return(
        <>
          {/*set key for this root div*/}
          <div className="fade-in" key={data}>
           <p>{data}</p>
          </div>
          <button onClick={handleOnChange}>update</button>
        </>
    )
    
    
    

  2. You will need to add more stage and one useEffect to track when your stage change. Your code should be:

    const [data, setData] = useState(0);
    const [change, setChange] = useState(true);
    
    useEffect(() => {
    const changeStage = () => {
    setChange(true);
    setTimeout(() => {
      setChange(false);
    }, 1100); // Adjust the timeout duration equal to your animation time, in your case is 1100
    };
    changeStage()
    },[data])
    
    return(
      <>
        <div className={change?"fade-in":""}>
         <p>{data}</p> // this data will change by some event, I want the css animation to be triggered every time when data changes
        </div>
      </>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search