DEV Community

Cindy
Cindy

Posted on

Change Navbar Style on Scroll Using React and CSS

Recently, I've been working on improving the UI of a previous project. One cool thing I've learned is changing the style of the navbar when the user scrolls.

My project had a navbar with a white background on top of a website that already had a white background, so when users scrolled, the logo and navbar items looked like they were floating. To remove the 'floating' items and make the navbar more obvious, I changed the navbar's background color on scroll.

In the navbar component, I added

  componentDidMount() {
    window.addEventListener("scroll", this.handleScroll);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
  }

  handleScroll = () => {
    if (window.scrollY > 20) {
      document.querySelector(".navbar").className = "navbar 
      scroll";
    } else {
      document.querySelector(".navbar").className = "navbar";
    }
  };
  • Added an event listener to the window object to watch for when a user scrolls down from the top of the website.
  • The event listener is in the React lifecycle method componentDidMount so that it is only created once (when this component is created).
  • Also have componentWillUnmount to remove the event listener when the component is going to be removed from the DOM.
  • The handleScroll method will be called when a user scrolls. This method will add an additional className to the nav element, which I can then select in CSS to override the background-color.
    • window.scrollY is a property of the Window object that returns the number of pixels that the document is currently scrolled vertically. I used this property to detect when the user has scrolled past 20 pixels. When a user does so, the HTML will look like this
// scrollY > 20
<nav className="navbar scroll">


// VS
// scrollY = 0
<nav className="navbar">

Now that I have the scroll class, I can select it in the CSS file using the class name.

.navbar {
  background-color: #fff;
}

.scroll {
  background-color: #f1f1f1;
}

The scroll background-color will override the default background-color as long as scroll is under navbar in the CSS file.

Thanks for reading! :)

Top comments (2)

Collapse
 
bobbycrooz profile image
bobbycrooz •

damn man! this is just straight to the point, my question got answered straight up

Collapse
 
sagdish profile image
Sagdi Formanov •

Thanks! This is short and on point