Andrea D_
Andrea D_

Reputation: 2141

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?

Upvotes: 0

Views: 817

Answers (1)

donjus
donjus

Reputation: 103

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

Upvotes: 2

Related Questions