react-use/src/useLockBodyScroll.ts
streamich 9bb7047b73 feat: 🎸 keep global state of all useLockBodyScroll hooks
This change will keep document body locked as long as at least one hook
is enabled on the page. Maybe it makes sense to generalize this logic
for other side-effect hooks. One such hook could be useBlurBody that
blurs page - useful for modals and overlays.
2019-03-24 17:43:35 +01:00

31 lines
657 B
TypeScript

import {useEffect} from 'react';
let counter = 0;
let originalOverflow: string | null = null;
const lock = () => {
originalOverflow = window.getComputedStyle(document.body).overflow;
document.body.style.overflow = 'hidden';
};
const unlock = () => {
document.body.style.overflow = originalOverflow;
originalOverflow = null;
};
const increment = () => {
counter++;
if (counter === 1) lock();
};
const decrement = () => {
counter--;
if (counter === 0) unlock();
};
const useLockBodyScroll = (enabled: boolean = true) => {
useEffect(() => enabled ? (increment(), decrement) : undefined, [enabled]);
}
export default useLockBodyScroll;