I'm new in javascript react. I'm trying to implement when user scrolled down, the navbar would drop a shadow. but unfortunately it doesn't work at all, what did I do wrong??
I think there's a problem with my logic, or perhaps I do the whole code wrongly, if there's an problem with the code, please do tell me where did I do it wrong, thank you
The Code :
class Navbar extends Component {
constructor() {
super(); // super allows you to access parent class's methods and allows us to use "this." in constructor().
this.state = {
clicked: false,
scrolled: false,
}
// Note here too these bindings are necessary to make `this` work in the callback
// In general, we use binding whenever we use "setState" when handling an event
this.handleScroll = this.handleScroll.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleScroll = () => {
const offset = window.scrollY;
if (offset > 200) {
this.setState({scrolled : !this.state.scrolled})
}
}
handleClick = () => {
this.setState({ clicked: !this.state.clicked})
}
render() {
return(
<div className='mycontainer' onScroll={this.handleScroll}>
{/* Note here this.scroll.scrolled changes to this.state.scrolled */}
<nav className={this.state.scrolled ? "NavbarItems Scroll" : "NavbarItems"}>
<h1 className="navbar-logo">React <i className="fab fa-react"></i></h1>
<div className="menu-icon" onClick={this.handleClick}>
<i className={this.state.clicked ? "fas fa-times" : 'fas fa-bars'}></i>
</div>
<ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
{
MenuItems.map((items, index) => {
return (
<li key = {index}><a className={items.cName} href={items.url}>
{items.title}
</a></li>
);
})
}
</ul>
<p>{window.scrollY}</p>
</nav>
</div>
);
}
}
css :
.mycontainer {
top: 0;
left: 0;
width: 100%;
height: 200%;
}
.NavbarItems {
position: fixed;
width: 100vw;
height: 85px;
background-color: white;
transition: 0.2s;
display: flex;
align-items: center;
font-size: 1.2rem;
justify-content: center;
}
.Scroll {
box-shadow: 0px 1px 10px #999;
}