Search code examples
reactjsdomaddeventlistenerreferenceerror

ReferenceError: document is not defined in React app using document.addEventListener


I am making a React app and I am trying to use the browser api to detect if a user is on the app tab or another one.

document.addEventListener("visibilitychange", (event) => {
  if (document.visibilityState == "visible") {
    return;
  } else {
    console.log('user is not in this tab')
  }
}

I am getting this error:

ReferenceError: document is not defined

Is this because I am calling document from a React app?


Solution

  • You need to make sure that the component is rendered. Therefore you should use the useEffect Hook