1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import { useCallback, useEffect, useRef, useMemo } from 'react';
import { useScrollBarWidth } from '../use-scrollbar-width';
type Styles = {
overflow: string;
paddingRight: string;
};
/**
* React hook to lock/unlock the scroll on the body.
*
* @param {boolean} [isScrollLocked] - Should the scroll be locked?
*/
export const useScrollLock = (isScrollLocked = false) => {
const scrollbarWidth = useScrollBarWidth();
const initialStyles = useRef<Styles | null>(null);
const lockedStyles: Styles = useMemo(() => {
return {
overflow: 'hidden',
paddingRight: `calc(${
initialStyles.current?.paddingRight ?? 0
} + ${scrollbarWidth}px)`,
};
}, [scrollbarWidth]);
useEffect(() => {
const computedStyle =
typeof window === 'undefined'
? undefined
: window.getComputedStyle(document.body);
initialStyles.current = {
overflow: computedStyle?.overflow ?? '',
paddingRight: computedStyle?.paddingRight ?? '',
};
}, []);
const lockScroll = useCallback(() => {
document.body.style.overflow = lockedStyles.overflow;
document.body.style.paddingRight = lockedStyles.paddingRight;
}, [lockedStyles]);
const unlockScroll = useCallback(() => {
document.body.style.overflow = initialStyles.current?.overflow ?? '';
document.body.style.paddingRight =
initialStyles.current?.paddingRight ?? '';
}, []);
useEffect(() => {
if (typeof window === 'undefined') return undefined;
if (isScrollLocked) lockScroll();
return () => {
unlockScroll();
};
}, [isScrollLocked, lockScroll, unlockScroll]);
};
|