use-scroll-lock

Lock scroll at current position
Import

Usage

use-scroll-lock locks scroll at current position by setting document.body overflow to hidden.

import { useScrollLock } from '@mantine/hooks';
import { Button, Group } from '@mantine/core';
import { LockClosedIcon, LockOpen2Icon } from '@modulz/radix-icons';
function Demo() {
const [scrollLocked, setScrollLocked] = useScrollLock();
return (
<Group position="center">
<Button
onClick={() => setScrollLocked((c) => !c)}
variant="outline"
leftIcon={scrollLocked ? <LockClosedIcon /> : <LockOpen2Icon />}
>
{scrollLocked ? 'Unlock scroll' : 'Lock scroll'}
</Button>
</Group>
);
}

Scrollbars offset

In some operation systems scrollbars have width.

To offset that width use-scroll-lock adds padding-right equal to scrollbar width to body element when scroll is locked. However if you use elements with fixed position you will need to add right padding manually: padding-right: var(--removed-scroll-width, 0px)).

Definition

function useScrollLock<T extends HTMLElement = HTMLDivElement>(
lock?: boolean,
options?: { disableBodyPadding?: boolean }
): readonly [boolean, Dispatch<SetStateAction<boolean>>];