0

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?

Ankush Chauhan
  • 1,433
  • 2
  • 17
  • 22

1 Answers1

0

Ideally your header and section shouldn't be outside react, it should be in the first react component that gets rendered (generally the default component in App.js). That being said, in React you can get hold of these DOM nodes with Refs and then pass it along to the other react component or hook to interact with them.

  • I think you misunderstood my question. I was trying to draw a comparison between normal html and React components. The Header and section are both individual components, rendered through the App.js. As the header and section does not share a parent-child relationship, Ref forwarding is not possible. – Ankush Chauhan Mar 11 '20 at 16:30