How to create a responsive navbar in NEXT JS?

CodeWithMarishCodeWithMarish
4 min read

Hello friends today in this post, we are going to learn on implementing a responsive navbar in your NEXT JS Application. As navigation is one of the important part of your website which allows the visitors to explore your website, so better implementation of this navbar in desktop, tablet, mobile will help you improving accessibility of the website which in turn retains your website visitor. I will show how I implemented on my my website https://codewithmarish.com which is built on NEXT JS, let's get started.

Step1: Project Setup

Open your project in vscode or create a new NEXT JS project using below command in your terminal

$ npx create-next-app your_project_name

Create a new folder named components and under that create a new file Navbar.jsx, NavItem.jsx

Step2: Creating NavItem

Before starting with navbar we will write our NavItem as we need to use it in our navbar. Create a functional component with text, href and active as props and use Link from next/link to link pages.

import Link from "next/link";
const NavItem = ({ text, href, active }) => {
  return (
    <Link href={href}>
      <a
        className={`nav__item ${
          active ? "active" : ""
        }`}
      >
        {text}
      </a>
    </Link>
  );
};

export default NavItem;

Step3: Setting up Navbar

Now, for Navbar.jsx, inside a functional component, initialize constant menu item object list and two state variables navActive initalized to false, activeIdx initialized to -1 using useState hook and inside that return we will have a header tag followed by nav inside that we will put our logo/text, mobile menu bar & map through menu list constant and return NavItem which we created for each iteration and pass the values for props. We will call this setActiveIdx Functions to update activeIdx to the current navitem index. We will also setNavActive to true whenever mobile menubars is clicked.

import Link from "next/link";
import Image from "next/image";
import React, { useState } from "react";
import Logo from "./Logo";
import NavItem from "./NavItem";

const MENU_LIST = [
  { text: "Home", href: "/" },
  { text: "About Us", href: "/about" },
  { text: "Contact", href: "/contact" },
];
const Navbar = () => {
  const [navActive, setNavActive] = useState(null);
  const [activeIdx, setActiveIdx] = useState(-1);

  return (
    <header>
      <nav className={`nav`}>
        <Link href={"/"}>
          <a>
            <h1 className="logo">CodeWithMarish</h1>
          </a>
        </Link>
        <div
          onClick={() => setNavActive(!navActive)}
          className={`nav__menu-bar`}
        >
          <div></div>
          <div></div>
          <div></div>
        </div>
        <div className={`${navActive ? "active" : ""} nav__menu-list`}>
          {MENU_LIST.map((menu, idx) => (
            <div
              onClick={() => {
                setActiveIdx(idx);
                setNavActive(false);
              }}
              key={menu.text}
            >
              <NavItem active={activeIdx === idx} {...menu} />
            </div>
          ))}
        </div>
      </nav>
    </header>
  );
};

export default Navbar;

Step4: Adding styles to navbar

Now coming to styles part, we will use flex & position properties.For header we ave set position to sticky and top to 0. For bars we just set width & height with background color with some animation.For menu we will switch between position fixed in mobile and position unset for table & desktops using media query. I also added some minor transitions for nav item.

@import url('https://fonts.googleapis.com/css2?family=Work+Sans:wght@400;500;700&display=swap');
* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
  font-family: 'Work Sans', sans-serif;
}
a{
  text-decoration: none;
  color: inherit;
}
header{
  position: sticky;
  z-index: 30;
  top: 0;
}
nav{
  display: flex;
  padding: 16px;
  justify-content: space-between;
  align-items: center;
  background-color: #f1f1f1;
}
.nav__menu-bar{
  display: flex;
  flex-direction: column;
  row-gap: 6px;
  cursor: pointer;
}
.nav__menu-bar div{
  width: 40px;
  height: 4px;
  background-color: black;
  border-radius: 2px;
}
.nav__menu-list{
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 60px;
  width: 288px;
  row-gap: 24px;
  right: -288px;
  padding: 24px 16px;
  transition: all 0.2s;
  min-height: calc(100vh - 60px);
  background-color: #f1f1f1;
}
.nav__menu-list.active{
  right: 0;
}
.nav__link{
  font-size: 18px; 
  position: relative;
  transition: all 0.2s;
}

.nav__link:hover{
 font-weight: bold;
}

.center{
  min-height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}
@media screen and (min-width: 768px) {
  .nav__menu-bar{
    display: none;
  }
  .nav__menu-list{
    position: unset;
    flex-direction: row;
    min-height: fit-content;
    width: fit-content;
    column-gap: 24px;
    align-items: center;
  }
  .nav__link::before{
    content: '';
    position: absolute;
    width: 0%;
    height: 6px;
    bottom: -16px;
    left: 0;
    background-color: black;
    transition: all 0.2s;
  }

  .nav__link:hover:before{
   width: 100%;
  }
}

We have a video in youtube regarding this menu bar animation in one of our challenges, you can also try to implement it.

You can tweak position, width & animation as per your requirements.

Everything done, but still you navbar isn’t visible just forget to mention please use this Navbar component in your index.js.

import Navbar from '../components/Navbar';

export default function Home() {
  return <div>
      <Navbar/>
    </div>
}

Finally, just create some empty pages for created links to test out otherwise it will show 404 page when pages not found for that links.

Live demo is seen in https://codewithmarish.com

Please find the code on Github

Responsive Navbar | Github

That’s it from my end friends, You would now have an idea of creating navbar in NEXT JS, apply your CSS skills to improve it.

If you found this post helpful please share maximum, Thanks for reading 😊 Stay tuned.

Also Please don’t forget to subscribe our youtube channel codewithmarish for all web development related challenges.

https://www.youtube.com/channel/UCkPYmdVz8aGRH6qCdKMRYpA

Posted with ❤️ from somewhere on the Earth

0
Subscribe to my newsletter

Read articles from CodeWithMarish directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

CodeWithMarish
CodeWithMarish

Hello guys! I am Marishwaran! Welcome to CodeWithMarish, where I post all things related to Full Stack Development. I'm dedicated to giving you the very best of Full Stack Development with a focus on quality and real-world problem solutions. Founded on Thu Feb 17 2022 by Marishwaran, CodeWithMarish has come a long way from its beginnings located in India. When I first started out, my passion for Full Stack Development drove me to start my own blogging site and build online web apps(products) using this knowledge. I hope you enjoy my blogging site and my web apps (products) as much as I enjoy offering them to you.