UNPKG

react-elegant-ui

Version:

Elegant UI components, made by BEM best practices for react

44 lines 1.31 kB
// Imported from yandex-ui. Source: https://github.com/bem/yandex-ui/ import { useRef } from 'react'; import { useIsomorphicLayoutEffect as useLayoutEffect } from '../hooks/useIsomorphicLayoutEffect'; import * as ScrollLocker from '../lib/scroll-locker'; /** * @example * const Modal: FC<ModalProps> = (props) => { * const { visible } = props; * const containerRef = useRef(document.documentElement); * * usePreventScroll({ enabled: visible, containerRef }); * * ... * } */ export function usePreventScroll(options) { var enabled = options.enabled, containerRef = options.containerRef; var elementRef = useRef(null); var lockedRef = useRef(false); useLayoutEffect(function () { var container = containerRef ? containerRef.current : null; if (elementRef.current === container) { return; } // Handle change ref object if (enabled && lockedRef.current) { ScrollLocker.unlock(elementRef.current); ScrollLocker.lock(container); } elementRef.current = container; }); useLayoutEffect(function () { if (!enabled) { return; } lockedRef.current = true; ScrollLocker.lock(elementRef.current); return function () { lockedRef.current = false; ScrollLocker.unlock(elementRef.current); }; }, [enabled]); }