forked from Creditra/Creditra-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseBodyScrollLock.ts
More file actions
42 lines (35 loc) · 1.25 KB
/
Copy pathuseBodyScrollLock.ts
File metadata and controls
42 lines (35 loc) · 1.25 KB
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
/**
* Locks body scroll while a modal/overlay is open.
* Prevents background content from scrolling on mobile/desktop.
* Restores scroll position and styles on close.
*/
import { useEffect } from 'react';
interface UseBodyScrollLockOptions {
/** Whether to lock scroll */
isLocked: boolean;
}
export function useBodyScrollLock({ isLocked }: UseBodyScrollLockOptions) {
useEffect(() => {
if (!isLocked) return;
// Save current scroll position and styles
const scrollY = window.scrollY;
const originalOverflow = document.body.style.overflow;
const originalPosition = document.body.style.position;
const originalWidth = document.body.style.width;
const originalTop = document.body.style.top;
// Lock scroll
document.body.style.overflow = 'hidden';
document.body.style.position = 'fixed';
document.body.style.width = '100%';
document.body.style.top = `-${scrollY}px`;
return () => {
// Restore scroll and styles
document.body.style.overflow = originalOverflow;
document.body.style.position = originalPosition;
document.body.style.width = originalWidth;
document.body.style.top = originalTop;
// Restore scroll position
window.scrollTo(0, scrollY);
};
}, [isLocked]);
}