DEV Community

venkata srikanth
venkata srikanth

Posted on

1 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay