I have a div and some component state representing whether or not that div is opened or closed.
When the state is !open
, the component is hidden by display: none
When state changes to open
, the component is now shown by changing to display: block
I slide the element into the screen. I do that through a keyframe animation.
@keyframes slide-in {
0% {
left: -100vw;
}
100% {
left: 0;
}
}
<div style={{ animation: slide-in 1s, display: open ? 'block' : 'none', position: 'absolute'}}>
This slides open when state is changed to open.
</div>
This works great when I’m going from closed -> open. However, there’s no animation at all for when I go from open -> closed. Which is slightly jarring. I tried but could not find a simple way to do this – so many ridiculous answers with hacky visibility changes or JS event listeners and class name changing.
I find it impossible to believe there’s a very simple way to go one direction, but not the other, when usually you want both.
Any help on this would be greatly appreciated!!
2
Answers
How about setting the position
not using the absolute left and right
value, but using transition? It’s more advisable to use css transition when applying an animationYou can play an animation in reverse by setting
animation-direction
, but it seems more like you want a transition?