Simple Dynamic Nav bar based on scroll position (React).

Alex Duterte
2 min readAug 9, 2020

I was trying to create a nav bar with a transparency that would become solid based on scroll position. For some reason I struggled trying to figure this out in React opposed to creating in vanilla javascript.

Using the useState and useEffect hooks, I was able to come up with something that works with a function component.

Now you see me, now you don’t

First, since I’m using a function component and not a class component, we need to import useState and useEffect hooks.

import { useState, useEffect } from "react"

We need state so we can compare where the scroll position is.

const [pos, setPos] = useState("top")// giving the default value of "top". I could have probably have used a boolean instead....

Next, we use the useEffect hook as a component did update lifecycle method.

useEffect (()=>{
document.addEventListener("scroll", e => {
let scrolled = document.scrollingElement.scrollTop;
if (scrolled >= 5){
setPos("moved")
} else {
setPos("top")
}
})
},[])

Within the useEffect function, we have an addEventListener that will check for a scroll event.

Next, we create a variable that checks the documents scroll position.

Then if the scrolled position is greater than 5 (or what ever you want) it will update state to “moved”.

The else portion of the if statement is for when the user scrolls back to the top of the page.

Putting it together

So now we a tracking the scroll position, we can do some conditional rendering.

<div className="nav" style={{backgroundColor: pos === "top" ? "rgba(0, 0, 0, 0)" : "rgba(0, 0, 0, .5)" }}>
// stuff inside the nav div
</div>

If the pos state value is “top”, the nav bar background will be transparent. If the pos state is not top, then you can set it to what ever rgba value you want.

Thats basically it. Hope this helps anyone trying to figure out how to accomplish this the “React” way.

--

--