React hook for listening to window scroll position
npm install @designbycosmic/cosmic-react-scroll-hook``
// from any functional component
import { useScrollPosition } from "cosmic-react-scroll-hook";
const ScrollWatcher = () => {
const { scrollX, scrollY } = useScrollPosition();
return (
The current scroll position is {x: ${scrollX}, y: ${scrollY}}
export default ScrollWatcher;
`
// from any functional componentimport { useScrollPosition } from "cosmic-react-scroll-hook";
const ScrollWatcher = () => {
const scrollableDiv = useRef({}); // Make sure to initialize ref with empty object
const { scrollX, scrollY } = useScrollPosition(scrollableDiv.current);
return (
...
);
}export default ScrollWatcher;
`You can also get direction of the scroll
`
// from any functional componentimport { useScrollPosition } from "cosmic-react-scroll-hook";
const ScrollWatcher = () => {
const scrollableDiv = useRef();
const { scrollingUp, scrollingDown, scrollingRight, scrollingLeft } = useScrollPosition();
...
}
export default ScrollWatcher;
``