Skip to content

Instantly share code, notes, and snippets.

@ellemedit
Last active April 7, 2020 09:49
Show Gist options
  • Save ellemedit/1e0e26fcf21f85ff29749ce9069cc458 to your computer and use it in GitHub Desktop.
Save ellemedit/1e0e26fcf21f85ff29749ce9069cc458 to your computer and use it in GitHub Desktop.
React hook for body scroll lock
import React from "react";
import { enableBodyScroll, disableBodyScroll, BodyScrollOptions } from "body-scroll-lock";
export const useScrollLock = (
targetElement?: HTMLElement | Element | null | false,
bodyScrollOption?: BodyScrollOptions
) => {
React.useLayoutEffect(() => {
if (!targetElement) {
return;
}
disableBodyScroll(targetElement, bodyScrollOption);
return () => {
enableBodyScroll(targetElement);
};
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [targetElement]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment