Skip to main content

useScrollLock

A custom hook that can lock and unlock the scroll of a specific element.

It can be used to lock the scroll of a background element (e.g., document.body) when a component such as a Modal is rendered.

By default, it automatically locks the scroll of document.body on mount.

On unmount, the target element's original overflow value is restored.


Code

🔗 View source code


Interface

typescript
interface UseScrollLockProps {
autoLock?: boolean;
}

const useScrollLock: <T extends HTMLElement>({
autoLock,
}?: UseScrollLockProps) => {
ref: React.MutableRefObject<Nullable<T>>;
lock: () => void;
unlock: () => void;
};

Options

NameTypeDefaultDescription
autoLockbooleantrueWhether to automatically lock scroll on mount

Returns

NameTypeDescription
refReact.MutableRefObject<Nullable<T>>Ref to attach to the target element. If not attached, document.body is used as the target.
lock() => voidFunction to lock scroll
unlock() => voidFunction to unlock scroll

Usage

document.body

typescript
import { useScrollLock } from '@modern-kit/react';

const Example = () => {
useScrollLock(); // Set { autoLock: false } to prevent automatic locking.

return <div>{/* ... */}</div>;
};

Specific element

typescript
import { useScrollLock } from '@modern-kit/react';

const Example = () => {
const { ref, lock, unlock } = useScrollLock<HTMLDivElement>({ autoLock: false });

const wrapperStyle = {
width: '400px',
maxHeight: '600px',
overflowY: 'scroll',
};
const boxStyle = {
width: '100%',
maxHeight: '500px',
};
return (
<div>
<button onClick={lock}>Lock Scroll</button>
<button onClick={unlock}>Unlock Scroll</button>
<div ref={ref} style={wrapperStyle}>
<div style={{ ...boxStyle, backgroundColor: 'red' }} />
<div style={{ ...boxStyle, backgroundColor: 'green' }} />
<div style={{ ...boxStyle, backgroundColor: 'blue' }} />
</div>
</div>
);
};

Example