@kimhongyeon/use-lock-body-scroll
Version:
A React hook to lock body scroll
40 lines (37 loc) • 1.48 kB
JavaScript
import { useRef, useEffect } from 'react';
var useLockBodyScroll = function (isLock, _a) {
var _b = _a === undefined ? {} : _a, _c = _b.lockDelay, lockDelay = _c === undefined ? 0 : _c, _d = _b.resetBodyScrollWhenLocking, resetBodyScrollWhenLocking = _d === undefined ? false : _d;
var lastScrollYRef = useRef(0);
useEffect(function () {
if (typeof window === 'undefined') {
return;
}
var release = function () {
document.body.style.removeProperty('overflow');
document.body.style.removeProperty('position');
document.body.style.removeProperty('width');
if (!resetBodyScrollWhenLocking) {
document.body.style.removeProperty('top');
}
setTimeout(function () {
window.scrollTo(0, lastScrollYRef.current);
}, 0);
};
if (isLock) {
lastScrollYRef.current = window.scrollY;
document.body.style.overflow = 'hidden';
setTimeout(function () {
document.body.style.position = 'fixed';
document.body.style.width = '100%';
if (!resetBodyScrollWhenLocking) {
document.body.style.top = "-".concat(lastScrollYRef.current, "px");
}
}, lockDelay);
}
else {
release();
}
return release;
}, [isLock]);
};
export { useLockBodyScroll };