@designbycosmic/cosmic-react-scroll-hook
v1.1.0
Published
React hook for listening to window scroll position
Downloads
3
Readme
cosmic-react-scroll-hook
React hook for listening to window scroll position
Typical use: getting scroll position of window
// from any functional component
import { useScrollPosition } from "cosmic-react-scroll-hook";
const ScrollWatcher = () => {
const { scrollX, scrollY } = useScrollPosition();
return (
<p>The current scroll position is {`x: ${scrollX}, y: ${scrollY}`}</p>
);
}
export default ScrollWatcher;
You can also get the scroll position of scrollable elements other than the window
// from any functional component
import { 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 (
<div ref={scrollableDiv}>
...
</div>
);
}
export default ScrollWatcher;
You can also get direction of the scroll
// from any functional component
import { useScrollPosition } from "cosmic-react-scroll-hook";
const ScrollWatcher = () => {
const scrollableDiv = useRef();
const { scrollingUp, scrollingDown, scrollingRight, scrollingLeft } = useScrollPosition();
...
}
export default ScrollWatcher;