Skip to content

Instantly share code, notes, and snippets.

@janicduplessis
Last active April 8, 2020 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janicduplessis/304290e0c337e4e5cc87449f13cad824 to your computer and use it in GitHub Desktop.
Save janicduplessis/304290e0c337e4e5cc87449f13cad824 to your computer and use it in GitHub Desktop.
import * as React from 'react';
export function useDisableBodyScroll(disabled: boolean): void {
const scrollPosition = React.useRef(0);
React.useEffect(() => {
// Don't do anything if scroll is already blocked somewhere else.
if (!disabled || document.body.style.position === 'fixed') {
return undefined;
}
scrollPosition.current = window.scrollY;
document.body.style.top = -window.scrollY + 'px';
document.body.style.left = '0';
document.body.style.right = '0';
document.body.style.overflowY = 'hidden';
document.body.style.overflow = 'hidden';
document.body.style.position = 'fixed';
return () => {
document.body.style.overflowY = 'initial';
document.body.style.overflow = 'initial';
document.body.style.position = 'initial';
document.body.style.top = '0';
window.scrollTo(0, scrollPosition.current);
};
}, [disabled]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment