Created
February 12, 2023 06:52
-
-
Save Tim-W-James/ee22239cc7d657045c5579bfa0910809 to your computer and use it in GitHub Desktop.
React useLockBodyScroll Custom Hook #hooks
This file contains hidden or 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
| const useLockBodyScroll = (): void => { | |
| // useLaoutEffect callback return type is "() => void" type | |
| useLayoutEffect((): (() => void) => { | |
| // Get original body overflow | |
| const originalStyle: string = window.getComputedStyle( | |
| document.body | |
| ).overflow; | |
| // Prevent scrolling on mount | |
| document.body.style.overflow = "hidden"; | |
| // Re-enable scrolling when component unmounts | |
| return () => (document.body.style.overflow = originalStyle); | |
| }, []); // Empty array ensures effect is only run on mount and unmount | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment