Skip to content

Commit e46c080

Browse files
Convert useLockBodyScroll to Typescript
1 parent ce4b269 commit e46c080

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/pages/useLockBodyScroll.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: useLockBodyScroll
44
date: "2019-01-15"
55
gist: https://gist.github.com/gragland/f50690d2724aec1bd513de8596dcd9b9
66
sandbox: https://codesandbox.io/s/yvkol51m81
7+
isMultilingual: true
78
links:
89
- url: https://jeremenichelli.io/2019/01/how-hooks-might-shape-design-systems-built-in-react/
910
name: How hooks might shape design systems built in React
@@ -61,3 +62,62 @@ function useLockBodyScroll() {
6162
}, []); // Empty array ensures effect is only run on mount and unmount
6263
}
6364
```
65+
66+
```typescript
67+
import { useState, useLayoutEffect } from "react";
68+
69+
// Usage
70+
function App() {
71+
// State for our modal
72+
const [modalOpen, setModalOpen] = useState<boolean>(false);
73+
74+
return (
75+
<div>
76+
<button onClick={() => setModalOpen(true)}>Show Modal</button>
77+
<Content />
78+
{modalOpen && (
79+
<Modal
80+
title="Try scrolling"
81+
content="I bet you you can't! Muahahaha 😈"
82+
onClose={() => setModalOpen(false)}
83+
/>
84+
)}
85+
</div>
86+
);
87+
}
88+
89+
90+
// Define modal props type
91+
type ModalProps = {
92+
title: string;
93+
content: string;
94+
onClose: () => void;
95+
}
96+
97+
function Modal({ title, content, onClose } : ModalProps) {
98+
// Call hook to lock body scroll
99+
useLockBodyScroll();
100+
101+
return (
102+
<div className="modal-overlay" onClick={onClose}>
103+
<div className="modal">
104+
<h2>{title}</h2>
105+
<p>{content}</p>
106+
</div>
107+
</div>
108+
);
109+
}
110+
111+
// Hook
112+
function useLockBodyScroll(): void {
113+
// useLaoutEffect callback return type is "() => void" type
114+
useLayoutEffect(() : () => void => {
115+
// Get original body overflow
116+
const originalStyle: string = window.getComputedStyle(document.body).overflow;
117+
// Prevent scrolling on mount
118+
document.body.style.overflow = "hidden";
119+
// Re-enable scrolling when component unmounts
120+
return () => (document.body.style.overflow = originalStyle);
121+
}, []); // Empty array ensures effect is only run on mount and unmount
122+
}
123+
```

0 commit comments

Comments
 (0)