HTML, CSS, NextJS – How can I prevent scroll freeze when a page is in desktop mode?

I have a single page application using NextJS.
I use useEffect to hide nav-menu by changing body className as below code:

const [ navbarOpen, setNavbarOpen ] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const handler = (e) => {
      if (
        navbarOpen &&
        ref.current &&
        !ref.current.contains(e.target)
      ) {
        setNavbarOpen(false);
      }
      
    };

    document.body.className = navbarOpen ? '' : 'mobile-nav-active';
    
  }, [navbarOpen]);

and CSS property:

.mobile-nav-active {
  overflow: hidden;
}

In desktop mode, when I click the menu, body className is changed to "mobile-nave-active" then I cannot scroll up or down.

How can I set the body property only in mobile mode?

Refer to page: https://mairesume.vercel.app

>Solution :

I think the problem is from this line of the code :

 document.body.className = navbarOpen ? '' : 'mobile-nav-active';

it works in desktop and mobile the same but the way that you are treating menu is different in each one,

if you add condition for mobile checking before assigning mobile-nav-active (because you don’t need it to be applied in desktop mode) your problem will be fixed

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   document.body.className = navbarOpen ? '' : 'mobile-nav-active';
}

Leave a Reply