Make Bootstrap’s Navbar Sticky in React with JavaScript
If you need instructions on how to setup Bootstrap’s navbar, follow the instructions on my previous post.
We’ll start by creating the Navigation component.
We needed to import the Navigation.css file since 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.
Dino Cajic is currently the Head of IT at LSBio (LifeSpan BioSciences, Inc.), Absolute Antibody, Kerafast, Everest BioTech, Nordic MUbio and Exalpha. He also serves as the CEO at MyAutoSystem. He has over a decade of software engineering experience. He has a B.S. in Computer Science and a minor in Biology. His background consists of creating enterprise level e-commerce applications, performing research based software development, and facilitating the spread of knowledge through writing.
You can connect with him on LinkedIn, follow him on Instagram, or subscribe to his Medium publication.