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 React from 'react';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 React, { useState } from 'react';import { useScrollLock } from '@mantine/hooks';import { Button } from '@mantine/core';import { LockClosedIcon, LockOpen2Icon } from '@modulz/radix-icons';export function Demo() {const [lockScroll, setLockScroll] = useState(false);useScrollLock(lockScroll);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></>);}
Disable touch events
To prevent scroll on mobile devices use disableTouchEvents
option.
Warning that this will prevent scroll in all all elements,
e.g. user will not be able to scroll modal content with overflow.
useScrollLock(true, { disableTouchEvents: true });
Definition
function useScrollLock(lock: boolean,options?: {disableTouchEvents: boolean;}): void;