@spaced-out/ui-design-system
Version:
Sense UI components library
53 lines (46 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useLockedBody = useLockedBody;
var _react = require("react");
function useLockedBody() {
let initialLocked = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
const [locked, setLocked] = (0, _react.useState)(initialLocked);
// Do the side effect before render
(0, _react.useLayoutEffect)(() => {
if (!locked) {
return;
}
// Save initial body style
const originalOverflow = document.body?.style.overflow || '';
const originalPaddingRight = document.body?.style.paddingRight || '';
// Lock body scroll
if (document.body) {
document.body.style.overflow = 'hidden';
}
// Get the scrollBar width
// TODO(Nishant): Fetch the scrollBar width from the browser
const scrollBarWidth = 0;
// Avoid width reflow
if (!!scrollBarWidth && document.body) {
document.body.style.paddingRight = `${scrollBarWidth}px`;
}
return () => {
if (document.body) {
document.body.style.overflow = originalOverflow;
}
if (!!scrollBarWidth && document.body) {
document.body.style.paddingRight = originalPaddingRight;
}
};
}, [locked]);
// Update state if initialValue changes
(0, _react.useEffect)(() => {
if (locked !== initialLocked) {
setLocked(initialLocked);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialLocked]);
return [locked, setLocked];
}