DEV Community

venkata srikanth
venkata srikanth

Posted on

The listener function is not registered in the functional components

react

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here is the code sandbox link

Top comments (0)