-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Showing
2 changed files
with
42 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,30 @@ | ||
import {useRef, useEffect} from 'react'; | ||
import {isClient} from './util'; | ||
import useUnmount from './useUnmount'; | ||
import {useEffect} from 'react'; | ||
|
||
const useLockBodyScroll = (enabled: boolean = true) => { | ||
const originalOverflow = useRef( | ||
isClient ? window.getComputedStyle(document.body).overflow : 'visible' | ||
); | ||
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; | ||
}; | ||
|
||
useEffect(() => { | ||
document.body.style.overflow = enabled ? "hidden" : originalOverflow.current; | ||
}, [enabled]); | ||
const increment = () => { | ||
counter++; | ||
if (counter === 1) lock(); | ||
}; | ||
|
||
useUnmount(() => { | ||
document.body.style.overflow = originalOverflow.current | ||
}); | ||
const decrement = () => { | ||
counter--; | ||
if (counter === 0) unlock(); | ||
}; | ||
|
||
const useLockBodyScroll = (enabled: boolean = true) => { | ||
useEffect(() => enabled ? (increment(), decrement) : undefined, [enabled]); | ||
} | ||
|
||
export default useLockBodyScroll; |