loading...
Cover image for sticky navbar on scroll reactJS

sticky navbar on scroll reactJS

abodmicheal profile image Abod Micheal (he/him) ・1 min read

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

Discussion

pic
Editor guide
Collapse
sapardo profile image
Sebastian Pardo

Hey, a newbie here. Got a question with your React code.
Shouldn't you have a constructor inside a class component??

Collapse
abodmicheal profile image
Abod Micheal (he/him) Author

only if you're passing prop

Collapse
sapardo profile image
Sebastian Pardo

ahhh i see!
Thanks for your response. ♥

Thread Thread
abodmicheal profile image
Abod Micheal (he/him) Author

wish you luck , react is actually easy and interesting, All the best

Collapse
nescalan profile image
nescalan

Good work, thank you

Collapse
talah221 profile image
talah221

Great rhanks