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
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.
You will need to add more stage and one useEffect to track when your stage change. Your code should be: