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
Interface
typescript
interface UseScrollLockProps {
autoLock?: boolean;
}
const useScrollLock: <T extends HTMLElement>({
autoLock,
}?: UseScrollLockProps) => {
ref: React.MutableRefObject<Nullable<T>>;
lock: () => void;
unlock: () => void;
};
Options
| Name | Type | Default | Description |
|---|---|---|---|
autoLock | boolean | true | Whether to automatically lock scroll on mount |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.MutableRefObject<Nullable<T>> | Ref to attach to the target element. If not attached, document.body is used as the target. |
lock | () => void | Function to lock scroll |
unlock | () => void | Function 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>
);
};