0

I'm trying to use IntersectionObserver with React. What I'm trying to do is to get a function to run when the bottom 25% of a div comes into view.

I created a createObserver function and wrapped it in a useEffect so that a the interSection observer won't assign a value to target or root until the component mounts.

useEffect(() => {
    createObserver();
  }, []);

Then I created the Intersection observer function, gave it a target to monitor and a root to compare the target against

const createObserver = () => {
    let options = {
      root: document.querySelector('.home'),
      rootMargin: '0px',
      threshold: 0.75
    }

    let target = document.querySelector("#align");

    let observer = new IntersectionObserver(() => {
        alert('helloWorld');
    }, options);

    observer.observe(target);
  }

The desired outcome is that the function should alert helloWorld when the bottom 75% of the div with an id of align comes into view. Instead it alerts helloWorld immediately the component mounts the DOM and that's it.

Here's a minimal reproducible example in case you'd like to test it out yourself:

const Home = () => {
   const createObserver = () => {
    let options = {
      root: document.querySelector('.home'),
      rootMargin: '0px',
      threshold: 0.75
    }
    let target = document.querySelector("#align");
    let observer = new IntersectionObserver(() => {
     alert('helloWorld')
    }, options);
    observer.observe(target);
  }

  useEffect(() => {
    createObserver();
  }, []);  

  return (
    <div className="home  col-sm-12">
      <div className="row" id="align"></div>
    </div>
  );
};
Opp
  • 520
  • 1
  • 8
  • 21
  • 1
    https://stackoverflow.com/help/minimal-reproducible-example – Roberto Zvjerković Aug 30 '20 at 08:07
  • Per this question, https://stackoverflow.com/q/53214116/2763250, apparently when you instantiate `IntersectionObserver`, the callback will be fired. – Anthony Aug 30 '20 at 16:33
  • Hello, @Anthony could you take a look at my question? https://stackoverflow.com/questions/75204977/intersectionobserver-to-create-a-lazy-load-images-with-data-srcset-and-imagekit – Sophie Jan 24 '23 at 11:54

0 Answers0