This is a custom hook for react which is useful to detect scroll direction in React applications in an efficient way with a custom threshold.
This package is created on behalf of a StackOverflow answer which draws some attention to itself, so if someone just wants something to work with right away, they can access it easily here.
To install it you can simply do the following command:
npm i @smakss/react-scroll-direction
or
yarn add @smakss/react-scroll-direction
to include it with common js module you should do this:
var { useDetectScroll } = require("@smakss/react-scroll-direction");
and to include it with ECMAscript module you can simply do this one:
import { useDetectScroll } from "@smakss/react-scroll-direction";
then to use it within your application you can do it just like below:
The useDetectScroll custom hook will accept 3 input parameter:
thr
(number
): A number to indicate the threshold of firing scroll direction event, which is0
by default and only accepts a positive numeric value. If it gets a higher value the steps will be longer.axis
(string
): Indicate the page scroll axis, whether, in they
orx
axes, it isy
by default.scrollUp
(string
): A string value for the output of the custom hook if the scroll direction is upward. The default value isup
if the axis isy
andleft
if the axis isx
.scrollDown
(string
): A string value for the output of the custom hook if the scroll direction is downward. The default value isdown
if the axis isy
andright
if the axis isx
.still
(string
): default value for the direction when there is no scrolling happening on the page. The default value isstill
.
const [scrollDir] = useDetectScroll({});
// scrollDir: "up"/"down"
const [scrollDir] = useDetectScroll({ axis: "x" });
// scrollDir: "left"/"right"