skip to Main Content

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


  1. You can use useEffect hook to run your query selector code after the component is mounted and the DOM is ready.

    For example:

    useEffect(() => {
      var checkExist = setInterval(function () {
        if ("#container".length) {
          let container = document.querySelectorAll("#container");
          let offbutton = container[0].querySelector("#offbutton");
        }
      }, 100);
      return () => clearInterval(checkExist);
    }, []);
    
    Login or Signup to reply.
  2. You probably need to call clearInterval in the return of a useEffect 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search