sticky navbar on scroll reactJS

abodmicheal

Abod Micheal (he/him)

Posted on October 12, 2020

sticky navbar on scroll reactJS

Basically showing how you could achieve the bellow Navbar in react .
Alt Text

firstly you need to create a file then name it Navbar,
add
import from '.Navbar'
on your App or Home component,
then go to the Navbar page you created and paste the below code

import React from 'react'
import './Navbar.css'
class Navbar extends React.Component {
  listener = null;
  state = {
    nav:false
  }
  componentDidMount() {
     window.addEventListener("scroll", this.handleScroll);
   }
   componentWillUnmount() {
      window.removeEventListener('scroll');
    }
   handleScroll= () => {
     if (window.pageYOffset > 140) {
         if(!this.state.nav){
           this.setState({ nav: true });
         }
     }else{
         if(this.state.nav){
           this.setState({ nav: false });
         }
     }

   }

  render(){
  return (
    <div>
    <div className={`Nav ${this.state.nav && 'Nav__black'}`}>
    <img src='imgleftlink'/>
    <img src='imgrightlink' />
    </div>
    </div>
  );}
}
export default Navbar
Enter fullscreen mode Exit fullscreen mode

create a css file and paste the bellow code for css , edit header color to your taste

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.Nav {
  margin-left: -40px;
  position: fixed;
  z-index: 2;
}
img ~ img  {
  position: fixed;
  right: 10px;
  top:8px;
}
.Nav__logo{
  margin-top: 12px;
}
.Nav__black{
  z-index: 2;
  background: rgba(0, 0, 0, 0.95);
  width: 100%;
}

Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
abodmicheal
Abod Micheal (he/him)

Posted on October 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related