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>
);
};