UNPKG

@spaced-out/ui-design-system

Version:
52 lines (45 loc) 1.46 kB
"use strict"; 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); } }, [initialLocked]); return [locked, setLocked]; }