0

My react web app has multiple components being rendered on a page. When the user has scrolled enough that a particular component/div has come into view, it should perform some action, say, console.log() for now. This event should only fire once the first time not over and over as they scroll up and down.

So as per my example, I have a component with a gray background. As soon as the heading inside that component comes into view, a single event should be fired. As the user keeps on scrolling down and the heading goes out of view, it should not fire any event.

With my current working implementation, on scrolling, the console event is fired as soon as the desired component comes into view. But instead of being fired only once, it keeps on firing the event continuously even when the desired component goes out of view.

Here is the link to what I was able to achieve so far:

https://codesandbox.io/s/wild-water-8l056?file=/src/componentTrack.js

This all seems to work fine only in code sandbox, but not in actual implementation. Any help to resolve it is appreciated.

program_bumble_bee
  • 439
  • 2
  • 25
  • 57

1 Answers1

1

The reason that you console log so many times is that the scrollHandler is called on each scroll event. You are checking for window.pageYOffset + window.innerHeight >= hiddenRef.current.offsetTop which is true when you scroll past the component.

I would suggest you look at this question and answer: React - check if element is visible in DOM and look into Intersection Observer: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Ondiek Elijah
  • 547
  • 8
  • 15