mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
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.
31 lines
657 B
TypeScript
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;
|