TL;DR
"Vanilla-JS app execute the code only if the user is active on the page, whereas React Components execute the code as soon as the component is loaded in the DOM (even if the user is not active on the page)"
I'm working on a React website and creating a SVG animations using "CSS Transitions" which gets triggered by adding a class to the element. Below is the React code
useEffect(() => {
function startAnimation() {
var wrapper = document.querySelector('svg#logo');
wrapper.classList.add('active');
}
}, []);
I initially created this in a Vanilla-JS project (using jQuery's $(document).ready()
function) and then converted that into a React Component. But I noticed that the transition in Vanilla-JS app gets initiated only if the page is active, whereas the React Components initiates the transition as soon as the component is loaded in the DOM (even if the user is not active on the page).
I understand that this is because I'm using the useEffect
hook, but how can we get the same behavior like $(document).ready()
using React?
Below is the Vanialla-JS Code
$(document).ready(function () {
function logoDraw() {
var wrapper = document.querySelector('svg#logo')
wrapper.classList.add('active')
}
setTimeout(logoDraw, 10)
});
Update:
- Based on the answer from another question, I used the "focus" event listener to start the animation only when the page is in focus. But after doing this, the transition is not getting initiated if I reload the page and stay in the same page. Its only getting initiated if I switch tabs.
- I found a related question which states that "On first load of the page it already has focus, therefore no event is raised"