body-scroll-lock: Does not work in gatsby projects

In order to lock the scrolling in a gatsby project, the overflow: hidden style property must be set on the root <html style="overflow: hidden;"> element.

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 5
  • Comments: 21

Most upvoted comments

I had to do this:

// for disabling
React.useEffect(() => {
    document.getElementsByTagName("html")[0].style.overflow = "hidden";
    disableBodyScroll(document.body);
  }, []);

// for enabling
React.useEffect(() => {
    enableBodyScroll(document.body);
    document.getElementsByTagName("html")[0].style = "";
  }, []);

@AidanRRR Can you try replacing all instances of document.body with document.documentElement in body-scroll-lock and see if that helps?

I was also having this problem, in Gatsby v2.32.10, with body-scroll-lock v3.1.5. My requirement was to lock the scroll when a modal side-navigation “drawer” was open.

The solution in https://github.com/willmcpo/body-scroll-lock/issues/154#issuecomment-612664227 improved the situation, but I also had to dynamically set the height style of the #gatsby-focus-wrapper div, like this:

  const [isOpen, setIsOpen] = useState(false); // represents the open state of the navigation drawer
  const headerEl = useRef();

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const gatsbyDiv = document.getElementById('gatsby-focus-wrapper');

    if (isOpen) {
      gatsbyDiv.style.height = '100%';
      document.documentElement.style.overflow = 'hidden';

      disableBodyScroll(headerEl.current);
    } else {
      gatsbyDiv.style.height = 'auto';
      document.documentElement.style.overflow = 'auto';

      enableBodyScroll(headerEl.current);
    }

    return clearAllBodyScrollLocks();
  }, [isOpen]);