Basically showing how you could achieve the bellow Navbar in react .
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
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%;
}
Top comments (11)
Thanks! I created a version for functional components:
const [show, setShow] = useState(false);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
const handleScroll = () => {
setShow(window.pageYOffset > 140);
};
nice thanks for that I'll add and give credit , working on a library for it
Hey, a newbie here. Got a question with your React code.
Shouldn't you have a constructor inside a class component??
only if you're passing prop
ahhh i see!
Thanks for your response. ♥
wish you luck , react is actually easy and interesting, All the best
Good work, thank you
Wasn't able to run this. Probably due to out of date?
still used it today for a project
I made a library out of this, check it out
Great rhanks