Я пытаюсь отслеживать видимость элемента с помощью React / Hooks и API Intersection Observer. Тем не менее, я не могу понять, как настроить наблюдение с помощью «useEffect». Кто-нибудь знает, как я могу это сделать? Мой раствор не работает ...
function MainProvider({ children }) {
const [targetToObserve, setTargetToObserve] = useState([]);
window.addEventListener("load", () => {
const findTarget = document.querySelector("#thirdItem");
setTargetToObserve([findTarget]);
});
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.intersectionRatio === 0.1) {
console.log("It works!");
}
},
{
root: null,
rootMargin: "0px",
threshold: 0.1
}
);
if (targetToObserve.current) {
observer.observe(targetToObserve.current);
}
}, []);
return (
<main>
<div className="Section-item" id="firstItem"></div>
<div className="Section-item" id="secondItem"></div>
<div className="Section-item" id="thirdItem"></div>
</main>
);
}