@kimhongyeon/use-lock-body-scroll
Version:
A React hook to lock body scroll
42 lines (38 loc) • 1.51 kB
JavaScript
;
var react = require('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 = react.useRef(0);
react.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]);
};
exports.useLockBodyScroll = useLockBodyScroll;