raddix

useScrollPosition

The useScrollPosition hook returns the current scroll position of the document or element.

Installation

npm i @raddix/use-scroll-position

Usage

Get scroll position of document

In this example, we get the scroll position of the document.

import { useScrollPosition } from '@raddix/use-scroll-position';
const App = () => {
const { x, y } = useScrollPosition();
return (
<div>
<p>Scroll position: {x}px, {y}px</p>
</div>
);
};

Get scroll position of element

To get the scroll position of a scrollable element, instead of the document, we can pass ref to the target option.

import { useRef } from 'react';
import { useScrollPosition } from '@raddix/use-scroll-position';
const App = () => {
const ref = useRef<HTMLDivElement>(null);
const { x, y } = useScrollPosition({ target: ref });
return (
<div ref={ref}>
<p>Scroll position: {x}px, {y}px</p>
</div>
);
};

API

Parameters

The useScrollPosition hook accepts a single object parameter with the following options:

OptionsDescriptionType
targetThe element to get the scroll position from.RefObject

Return value

The useScrollPosition hook returns an object with two properties:

Return valueDescriptionType
xThe horizontal scroll position.number
yThe vertical scroll position.number