Make Bootstrap’s Navbar Sticky in React with JavaScript

Image for post
Image for post
Sticky Navigation shown at the top of the screen

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.

Written by

Author of An Illustrative Introduction to Algorithms. A Software Engineer with a B.S. in Computer Science, a minor in Biology, and a passion for learning.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store