The following code using IntersectionObserver in simple Html & JavaScript works fine to change the header styling depending on the visibility of a section just below the header. Reference
observer.js
const header = document.querySelector("header");
const sectionOne = document.querySelector(".home-intro");
const sectionOneOptions = {
rootMargin: "-200px 0px 0px 0px"
};
const sectionOneObserver = new IntersectionObserver(function(
entries,
sectionOneObserver
) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
header.classList.add("nav-scrolled");
} else {
header.classList.remove("nav-scrolled");
}
});
},
sectionOneOptions);
sectionOneObserver.observe(sectionOne);
The above observer.js file targets the elements referred in the index.html below.
index.html
<header>…Some nav links</header>
<section class="home-intro">...</section>
<script src="js/observers.js"></script>
Now, I want to achieve this functionality in my React app. The question here is that in the above implementation, both the observer(sectionOne) and target(header) are in same html file but in my React app the observer(some section or div) and the target(header) are in their separate components.
So, in which component should I create this IntersectionObserver - Header(target) component or the component having the section(observer) and how do I refer the other one?