If you need instructions on how to setup Bootstrap's navbar, follow my previous post.
We'll start by creating the Navigation component.
We needed to import the Navigation.css file. This is where we'll create our sticky CSS class.
We created our variables, navbar and sticky. They will be initialized after the page renders. Next, we'll need to add the componentDidMount() lifecycle method to the Navigation class. This will initialize the navbar and sticky variables and add the scroll event listener to our navigation.
The event listener will call the handle sticky function. We also add the componentWillUnmount() lifecycle method to remove the event listener.
And that's it. It should work just like Bootstrap 4's sticky-top class.
We'll start by creating the Navigation component.
import React from 'react';
import './Navigation.css';
let navbar;
let sticky;
class Navigation extends React.Component {
render() {
return(
<nav
id="main-navigation"
className="navbar navbar-expand-lg navbar-light"
>
...
We needed to import the Navigation.css file. This is where we'll create our sticky CSS class.
/* The sticky class is added to the navbar with JS when it
reaches its scroll position */
.sticky {
position: fixed;
top: 0;
width: 100%;
z-index: 100;
}
We created our variables, navbar and sticky. They will be initialized after the page renders. Next, we'll need to add the componentDidMount() lifecycle method to the Navigation class. This will initialize the navbar and sticky variables and add the scroll event listener to our navigation.
class Navigation extends React.Component {
componentDidMount() {
navbar = document.getElementById("main-navigation");
sticky = navbar.offsetTop;
window.addEventListener('scroll', this.handleSticky);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleSticky);
}
The event listener will call the handle sticky function. We also add the componentWillUnmount() lifecycle method to remove the event listener.
class Navigation extends React.Component {
componentDidMount() {
navbar = document.getElementById("main-navigation"); // Get the navbar
sticky = navbar.offsetTop; // Get the offset position of the navbar
window.addEventListener('scroll', this.handleSticky);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleSticky);
}
/**
* Adds the sticky CSS class to the navbar when it reaches the top of it
*/
handleSticky = () => {
if (window.pageYOffset > sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
And that's it. It should work just like Bootstrap 4's sticky-top class.
react js with redux react js with redux</a
ReplyDelete