ReferenceError: document is not defined - How to solve it?

Hi Friends!

To prevent scrolling on a mobile menu I would like to set the body tag to overflow: hidden; just when the the mobile menu is active. Therefore I like need to make an if statement like in the example

  if (mobileMenu) {
    document.body.classList.add('active-modal');
  } else {
    document.body.classList.remove('active-modal');
  }

This error messages shows up:

I already searched for solutions and here is a great article about how to solve it. BUT ANYWAY I was not able to fix it with this solution, so I would like to ask for help…

I know that this is a common issue and a beginners challenge…

Please let me know how to fix this for dummies! :laughing:

Thank you!!

It’s impossible to propose a solution seeing only three lines of code. I’d say wrap it in useEffect, but I can’t tell what “it” is.

@jenovs thanks for your answer! Actually you gave me the keyword WRAP and finally it works, but it is not working with useEffect

This example is NOT working:

  useEffect(() => {
    alert('Finished loading');

    if (mobileMenu) {
      document.body.classList.add('active-modal');
    } else {
      document.body.classList.remove('active-modal');
    }
  }, []);

This works:

 if (typeof window === 'object') {
    // Check if document is finally loaded
    document.addEventListener('DOMContentLoaded', function () {
      alert('Finished loading');
    });
    if (mobileMenu) {
      document.body.classList.add('active-modal');
    } else {
      document.body.classList.remove('active-modal');
    }
  }

Any ideas why the first example isn´t working but the second is?

Try adding mobileMenu to the dependencies array.

useEffect(() => {
  if (mobileMenu) {
    document.body.classList.add('active-modal');
  } else {
    document.body.classList.remove('active-modal');
  }
}, [mobileMenu]);
1 Like

Oh I see, the dependency arrey :laughing: