I have one small component, with some text.
In useEffect, I am simply setting the top of the element to some values.
CSS:
.box {
display: flex;
flex-direction: column;
position: relative;
top: 0;
transition: top 0 ease-in;
}
useEffect(() => {
setTimeout(()=> { // with this it is working.
const elems = document.getElementsByClassName("box");
[...elems].forEach(function (e) {
e.style.top =`-200px`; // without settimeout transition is not working
});
});
}, []);
My Markup:
<div className='progress'>
<div className='box' />
<div className='box' />
<div className='box' />
</div>
Now when I do frequent refreshes, I see the transition happening a few times, but not every time.
But when I wrap my code in setTimeout I see a transition every time.
I am not sure why is this happening.
2
Answers
The browser might not have time to apply the initial state before transitioning to the new state. The setTimeout introduces a delay, giving the browser time to apply the initial state and then transition to the new state.
I have no idea about React but what you are trying to do is relatively striaghtforward with
@keyframes
. There is no need to usesetTimeout()
. Here is a snippet that you can modify: