Skip to content

Instantly share code, notes, and snippets.

@aandrewww
Last active May 24, 2020 16:19
Show Gist options
  • Save aandrewww/5ea5e2c071240e07fb3636c69cfc7d32 to your computer and use it in GitHub Desktop.
Save aandrewww/5ea5e2c071240e07fb3636c69cfc7d32 to your computer and use it in GitHub Desktop.
import { useCallback } from 'react';
export const usePreventPageScroll = () => {
const enable = useCallback(() => {
// Prevent scrolling
document.body.style.position = 'fixed';
document.body.style.top = `-${window.scrollY}px`;
}, []);
const disable = useCallback(() => {
// Re-enable scrolling
document.body.style.position = '';
document.body.style.top = '';
window.scrollTo(0, parseInt(window.getComputedStyle(document.body).top || '0', 10) * -1);
}, []);
return {
enable,
disable,
};
};
@aandrewww
Copy link
Author

aandrewww commented May 24, 2020

const onModalOpened = useCallback(() => {
  if (onOpened) {
    onOpened();
  }

  if (scrollable) {
    scrollEnable();
  }

  document.body.classList.add(MODAL_SHOWN_CLASS);
}, [onOpened, scrollable, scrollEnable]);

const onModalClosed = useCallback(() => {
  if (onClosed) {
    onClosed();
  }

  if (scrollable) {
    scrollDisable();
  }

  document.body.classList.remove(MODAL_SHOWN_CLASS);
}, [onClosed, scrollable, scrollDisable]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment