React - how to get element offset position

Assuming a layout like this:

class App extends Component {
 state = {}

 render() {
   <Hero />
    <About />
    <Contact />
   <Footer />

I’d like to get the offsetTop position of the most parent div element from the About component. I need this value to show a sticky navbar when the user scrolls to certain area of the layout, I could hard code the number but this is not reliable because the size of the screen can change based on the client’s screen size device.

TLDR; How can I get an element offsetTop position?

Why not just add that component where you want it and render it conditionally?

In any case, there is discussion here about finding position.

To render the navbar conditionally I need the offset of the about section. The navbar fades in when the user scrolls down specifically to the about section.

I could hard code the value but that’s not a good idea because the screen size can change, I need it to be consistent.

If you want to get the offsetTop of your parent element, you just need to place it with a unique id for identity at your scripts for doing sticky navbar.

<main id="sticky-container">

and after that, you can using pure JavaScript to detect above element’s offsetTop:

var stickyContainer = document.getElementById("sticky-container");
console.log(stickyContainer && stickyContainer .offsetTop ? .offsetTop : 0);

Hope you get the best solution!!

Materials and Tutorials you can find on my Youtube channel to learn everything you want and will be up-to-date:
youtube dot com/channel/UCg7GE5bWGvBGnvjt7ZiL04g

Happy New Year 2019!!!

Umm I don’t think I should be targeting DOM elements in React, I was hoping I could this in a React way.

To render the navbar conditionally I need the offset of the about section.

I don’t understand this sentence. And you can create fades and animations without knowing the offset. I think your premise is off.

I have the fade animation, the thing is that the fade in animation kicks in when the user scrolls down to a certain area of the webpage.

So to know when to kick in the fade animation I need the offsetTop position of a given element. I could very well just do

if (window.pageYOffset > 780) { //do something }

But as I said, with this approach it wouldn’t be consistent because the screen size can change. So I was wondering if I could get the offset position of an element and use that instead.

I think I know what you mean.

You can find the height of the window with window.innerHeight

  if (window.pageYOffset > window.innerHeight) { do your thing! }

I’m super late to this game…