diff --git a/snippets/useBodyScrollLock.md b/snippets/useBodyScrollLock.md new file mode 100644 index 000000000..f6209028c --- /dev/null +++ b/snippets/useBodyScrollLock.md @@ -0,0 +1,61 @@ +--- +title: useBodyScrollLock +tags: hooks,effect,intermediate +firstSeen: 2021-09-02T05:00:00-04:00 +--- + +Enables body scroll locking. + +- Use the `useLayoutEffect()` with an empty array as the second argument to execute the provided callback only once when the component is mounted. +- Use `Window.getComputedStyle()` to get the `overflow` value of the `body` element and store it in a variable. +- Replace the `overflow` value of the `body` element with `'hidden'` and restore it to its original value when unmounting. + +```jsx +const useBodyScrollLock = () => { + React.useLayoutEffect(() => { + const originalStyle = window.getComputedStyle(document.body).overflow; + document.body.style.overflow = 'hidden'; + return () => (document.body.style.overflow = originalStyle); + }, []); +}; +``` + +```jsx +const Modal = ({ onClose }) => { + useBodyScrollLock(); + + return ( +
+

+ Scroll locked!
Click me to unlock +

+
+ ); +}; + +const MyApp = () => { + const [modalOpen, setModalOpen] = React.useState(false); + + return ( +
+ + {modalOpen && setModalOpen(false)} />} +
+ ); +}; + +ReactDOM.render(, document.getElementById('root')); +```