new to react. I was wondering why my React page A was showing query selector error of page B. The error loops like infinite times until I route to Page B.
Code in page B
var checkExist = setInterval(function() {
if (('#container').length) { //if container div exists
let container = document.querySelectorAll("#container")
let offbutton = container[0].querySelector('#offbutton')
}
}, 100);
Only shows error when not in page B
2
Answers
You can use
useEffect
hook to run your query selector code after the component is mounted and the DOM is ready.For example:
You probably need to call
clearInterval
in the return of auseEffect
function so that the timer is cleared when your component "B" is unmounted.The timer still running should be causing the error when you are not in component B.