Using Functional Component, I am trying to find the scroll position of an element, but the listener function isn't registering as scrolling occurs. Can anyone explain why this is happening.
Here is the code for reference
export default function App() {
const [scrollPosition, setScrollPOsition] = useState(0);
const innerRef = useRef<HTMLParagraphElement>(null);
const handleScroll = () => {
console.log("handle scroll");
// setScrollPOsition((scrollPosition) => scrollPosition + 1);
};
useEffect(() => {
if (innerRef.current) {
innerRef.current.addEventListener("scroll", handleScroll);
return () => innerRef.current?.addEventListener("scroll", handleScroll);
}
}, []);
return (
<div className="App">
<span className={"scrollValue"}>
scroll position of first header: {scrollPosition}
</span>
<h1 ref={innerRef}>Find My position on window</h1>
<h2>Heading Element</h2>
...
...
<h2>Heading Element</h2>
</div>
);
}
Here is the code sandbox link
If you want to listen on the current scroll position you would make use of the onScroll
event attribute.
I gave your scrolling <div>
the innerRef
and passed in handleScroll
to your divs onScroll
.
<div className="App" ref={innerRef} onScroll={handleScroll}>
<span ...
Additionally I had to add a fixed height and overflow-y: scroll
to your .App
class for the scroll event to be triggered:
// styles.css
.App {
font-family: sans-serif;
text-align: center;
height: 500px;
overflow-y: scroll;
}