COVID19 Lockdown Dev Log – Day 8
What I Worked On
Hiding the navigationbar when scrolling, on my portfolio.
What I Learned
I learned how to implement functionality that hides your navigationbar on scroll using React.
Let’s implement it in my ‘navigation.js’ component. In the component state we add ”prevScrollPos: window.pageYOffset”. This will capture the current scroll position. We also add a boolean to check if the navbar should be visible like so “isVisible: true”. Depending on the boolean, a CSS class will be triggered, which hides or shows the navbar.
// navigation.js
import React, {Component} from "react";
class Navigation extends Component {
constructor(props) {
super(props);
this.state = {
toggleMenu: false,
prevScrollpos: window.pageYOffset,
isVisible: true
}
}
... some more code
Then we make a function, which will fire each time the user scrolls on the page:
// navigation.js
...code containing constructor and state
scrollShow = () => {
const { prevScrollPos } = this.state;
const currentScrollPos = window.pageYOffset;
const visible = prevScrollPos > currentScrollPos;
this.setState({
prevScrollPos: currentScrollPos,
isVisible: visible
});
}
Because the component will be mounting and unmounting everytime the user scrolls, we need to use the lifecycle methods, ‘componentDidMount’ and ‘componentWillUnmount’, to add and remove the scroll function:
// navigation.js
...code containing our constructor and 'scrollShow' function
componentDidMount() {
window.addEventListener("scroll", this.scrollShow);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.scrollShow);
}
Alright! Let’s bind the CSS class to the ‘isVisible’ state. We do that by adding it to the <nav> element. Using backticks “ we can easily insert JavaScript, which we will use to toggle the CSS class ‘hide-nav’:
// navigation.js
render() {
return (
<nav className={`navbar main-nav ${this.state.isVisible ? '': 'hide-nav'}`}>
... more code containing JSX
)
}
The CSS contains the styles for the navbar itself and then a seperate class, which will hide it:
// style.css
.main-nav {
position: fixed !important;
width: 100%;
top: 0;
transition: ease-in-out .3s;
}
.hide-nav {
top: -100px;
}
There! Now the navbar behaves like this when we scroll down:
What Distracted Me During The Day
- Messenger
- Went for “Friday cake” with the gf during lunch. 😀
- Emails