skip to Main Content

I’ve been looking for a solution for my problem for a bit and I can find many articles for similar issues, but nothing that quite solves my problem.

I have an app written in React. On the mobile version of the site users can click a hamburger menu to open a navigation menu. The nav menu takes up 80vw and 100vh. For some reason users are still able to scroll the application in the background by swiping the nav menu.

My mobile nav is styled as follows.

.mobileNav {
  height: 100vh;
  width: 0vw;
  position: fixed;
  top: 0;
  right: 0;
  background-color: #1d1d1d;
  z-index: 999;
  will-change: transform;

  -webkit-transition: 0.75s;
  -moz-transition: 0.75s;
  -ms-transition: 0.75s;
  -o-transition: 0.75s;
  transition: width 0.75s;

  &--open {
    width: 80vw;
  }
}

I have tried setting position: fixed or overflow: hidden to the parent element when the navBar is opened. This will prevent scrolling but also jumps the user to the top of the page which is undesirable.

Here is my jsfiddle https://codesandbox.io/s/react-fiddle-forked-p9fqc8?file=/src/App.js&resolutionWidth=492&resolutionHeight=675.

2

Answers


  1. Hi this is actually default behavior. What you have to do is write some code that makes the background unscrollable when the modal is open. Here is a quick read that might help:
    https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/

    Login or Signup to reply.
  2. const App = () => {
      const [isNavOpen, setIsNavOpen] = useState(false);
    
      useEffect(() => {
        document.body.style.overflow = isNavOpen ? "hidden" : "auto";
      }, [isNavOpen]);
    
      return (
        <div className="App">
          <NavMenu isNavOpen={isNavOpen} setIsNavOpen={setIsNavOpen} />
          <div className={styles.red}>
            Hello <button onClick={() => setIsNavOpen(true)}>Open</button>
          </div>
          <div className={styles.blue}>Hello</div>
          <div className={styles.green}>Hello</div>
        </div>
      );
    };
    
    export default App;
    
    

    useEffect will fire every time the nav modal swaps between being open / closed. when it’s set to closed, we enable body scrolling. when it’s open, we disable body scrolling.

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