use-scroll-lock
Lock scroll at current position
Import
Source
Docs
Package
Usage
Use this hook when you want to prevent user from scrolling on document level, for example, with modals and drawers.
Example modal component, whenever modal is opened, scroll is locked at current scroll position. Hook accepts one argument – boolean value that controls if scroll is locked:
import { useScrollLock } from '@mantine/hooks';function Modal({ opened }) {useScrollLock(opened);if (!opened) {return null;}return <div>My modal</div>;}
Examples
When hooks is called with true
, it sets document.body.style.overflow
to hidden
.
When component is unmounted, scroll lock is automatically removed:
import { useScrollLock } from '@mantine/hooks';import { Button } from '@mantine/core';import { LockClosedIcon, LockOpen2Icon } from '@modulz/radix-icons';export function Demo() {const [lockScroll, setLockScroll] = useScrollLock();return (<ButtononClick={() => setLockScroll((c) => !c)}variant="outline"leftIcon={lockScroll ? <LockClosedIcon /> : <LockOpen2Icon />}>{lockScroll ? 'Unlock scroll' : 'Lock scroll'}</Button>);}
use-scroll-lock is used in some components in @mantine/core, example with Modal component:
import React, { useState } from 'react';import { Modal, Button, Group } from '@mantine/core';function Demo() {const [opened, setOpened] = useState(false);return (<><Modalopened={opened}onClose={() => setOpened(false)}title="Introduce yourself!"><AuthenticationForm /></Modal><Group position="center"><Button onClick={() => setOpened(true)}>Open Modal</Button></Group></>);}
Definition
function useScrollLock(lock?: boolean): readonly [boolean, React.Dispatch<React.SetStateAction<boolean>>];
Built by Vitaly Rtishchev and these awesome people