Thu Jan 07 2021

A sticky Navbar in React with 3 lines of code

Making a sticky navbar is no longer tedious thanks to the new Sticky CSS property! Learn how to do this with only 3 lines of code!

Quick disclaimer, I am going to make this article as short as possible since the code needed to make a Navbar sticky is only 3 lines.

Imagine that you have the below navbar component

1import React from "react";
2import styles from "../navbar/navbar.module.css";
3const Navbar = () => {
4 return (
5 <header className={styles.mobileNav}>
6 <nav>
7 <ul>
8 <li>
9 <a href="#">Home</a>
10 </li>
11 <li>
12 <a href="#">About</a>
13 </li>
14 <li>
15 <a href="#">FAQ</a>
16 </li>
17 <li>
18 <a href="#">Contact</a>
19 </li>
20 </ul>
21 </nav>
22 </header>
23 );
24};
25export default Navbar;
Pretty standard looking Navbar right? PS- I have not styled the the ul and li tags here to keep it simple. The only styling I would like to draw your attention to is the one on the header. The className={styles.mobileNav} is me styling the header with a CSS module (not sure what a CSS module is? Check my blogpost here).

The final step I will be doing to make this navbar sticky is to head over to the navbar.module.css and add the below CSS code

1.mobile-nav {
2 position: -webkit-sticky; /* Safari */
3 position: sticky;
4 top: 0;
5}

And that is it! Our navbar is now sticky!

On final note, are you worried about browser compatibility? Don't be. because MDN tells me that the sticky property is now supported across all browser except the old version of IE.

If you found what you read helpful, please let me know and follow me on my social media channels for more! If not, you can just sign up to my email newsletter below to be notified of any blog post I publish 😊

Comments