Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a CSS animation on EVERY TIME a react component re-renders

Tags:

css

reactjs

I want to play an animation on a react component every time it rerenders due to prop change:

react:

function Card({ cardText }) {
  return <div className="roll-out">{cardText}<div/>
}

So I did css:

@keyframes rollout {
  0% { transform: translateY(-100px); }
  100% { transform: none; }
}

.roll-out {
  animation: rollout 0.4s;
}

However, the animation only plays once, on the initial render. I want to play it every time <Card /> re-renders due to cardText change. How can I achieve it?

like image 370
Quuxuu Avatar asked Jul 31 '20 06:07

Quuxuu


1 Answers

Add a key like this:

function Card({ cardText }) {
  return <div key={cardText} className="roll-out">{cardText}<div/>
}

In your code, when the div re-renders, react only changes its inner text. Adding a key will make react think it's a different div when the key changes, so it'll unmount it and mount again.

like image 163
ZYinMD Avatar answered Nov 10 '22 19:11

ZYinMD