Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Create a Responsive Navbar Using ReactJS



Web Development usually focuses on the navbar and it is the primary mode of interaction with users - hence making a good navbar design an important element. Welcome back to another blog tutorial - Today we are gonna build a navbar that is both responsive and visually appealing using ReactJS. To make a professional and user-friendly web application, you must have an attractive navbar. We will begin with a simple React project and then build a responsive navbar using pre-designed styles to make it beautiful.

Prerequisites

  • React Basics: You must know about the basics around react components, state management, and hooks. If you have never used React before, it is important to start by reading the documentation so that you can learn what it actually is, and then find a beginner course.
  • Node.js and npm: Node version 6 or higher, together with NPM (the package manager of the js community), is used to build web-based front-end applications, such as Angular JS apps using Webpack. But, if you already have a node is good. js and npm (node package manager ) into your machine. We can download these by npm install. js website.
  • Code Editor: You can use any code editor of your choice on which you are familiar with writing as well as handling this react code.
  • React Application Setup: You should have a pre-configured and set React application. If you do not have any, it's one line step away from being created using the Create React App.

Steps to Create Responsive Navbar

Below mentioned guide below gives you a step-by-step procedure for creating your own responsive navbar.

Step 1: Setting up your React Environment

You need to have your react environment ready before going into the main code. If you do not have a react application then you can create one using 'create-react-app' command. Go to the folder where you want to create your react application open terminal/command prompt then type the below command. This command builds the react application at this place.

npx create-react-app responsive-navbar
cd responsive-navbar

Note: You can replace 'responsive-navbar' with your own preferred project name (following the project naming convention).

Step 2: Creating a Responsive Navbar Component

Inside the 'src' folder, create a new file called 'Navbar.js'.

import React, { useState, useEffect } from "react";
import "./Navbar.css";

const Navbar = () => {
  const [isMobile, setIsMobile] = useState(false);
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
      if (window.innerWidth > 768) {
        setIsMobile(false); // Close mobile menu when switching to a larger screen
      }
    };

    window.addEventListener("resize", handleResize);
    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return (
    <nav className="navbar">
        <div className="navbar-container">
            <h3 className="logo">BrandName</h3>
            <ul className={isMobile ? "nav-links-mobile" : "nav-links"}>
                <li>
                    <a href="#home" className="nav-link">
                        Home
                    </a>
                </li>
                <li>
                    <a href="#about" className="nav-link">
                        About
                    </a>
                </li>
                <li>
                    <a href="#services" className="nav-link">
                        Services
                    </a>
                </li>
                <li>
                    <a href="#portfolio" className="nav-link">
                        Portfolio
                    </a>
                </li>
                <li>
                    <a href="#contact" className="nav-link">
                        Contact
                    </a>
                </li>
            </ul>
            <div
                className="mobile-menu-icon"
                onClick={() => setIsMobile(!isMobile)}
            >
                <div className={`hamburger ${isMobile ? "active" : ""}`}>
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
        </div>
    </nav>
  );
};

export default Navbar;

Approach and Explanation

  • isMobile: This state variable determines whether the mobile menu (hamburger menu) is open or closed.
  • windowWidth: This state keeps track of the current width of the browser window. It is updated whenever the window is resized.
  • useEffect Hook: The useEffect hook is used to add an event listener to track changes in window size. This ensures that when the window is resized (e.g. when transitioning from mobile to desktop view), the mobile menu is automatically closed if the screen width exceeds 768px. This prevents the issue of the navbar remaining open when switching between screen sizes.
  • Rendering Logic: The component renders a Navbar(), which contains the logo and navigation links. The links are displayed as a horizontal list on larger screens (nav-links), and as a vertical list when the mobile menu is open (nav-links-mobile). The hamburger menu (mobile-menu-icon) is displayed only on mobile screens (or smaller screens). Clicking the hamburger icon toggles the isMobile state, which controls whether the mobile menu is shown.
  • Responsive Design: The navbar is designed to be fully responsive. The useEffect hook ensures that the menu closes automatically when the screen size changes. The isMobile state allows the component to dynamically switch between mobile and desktop views.
  • Styling: The CSS styles in Navbar.css provide a visually distinct and appealing black royal theme with smooth transitions, a box shadow for depth, and a golden border for a luxurious touch.

Step 3: Adding Styles for Responsive Navbar Component

The CSS demonstrated here is for a sample. So, create a file named 'Navbar.css' in the 'src' folder to style your responsive navbar component.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap");

body {
  font-family: "Poppins", sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: #121212;
  color: #ffffff;
}

.navbar {
  width: 100%;
  height: 70px;
  background: #000;
  background: linear-gradient(to right, #333, #000);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.6);
  border-bottom: 2px solid #ff9800;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.navbar-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo {
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 2px;
  cursor: pointer;
}

.nav-links {
  display: flex;
  align-items: center;
  list-style: none;
}

.nav-links li {
  margin: 0 20px;
}

.nav-link {
  color: #fff;
  text-decoration: none;
  font-size: 18px;
  position: relative;
  padding: 5px 0;
  transition: color 0.3s ease;
}

.nav-link::after {
  content: "";
  width: 0;
  height: 3px;
  background: #ff9800;
  position: absolute;
  left: 0;
  bottom: -5px;
  transition: all 0.3s ease;
}

.nav-link:hover {
  color: #ff9800;
}

.nav-link:hover::after {
  width: 100%;
}

/* Hamburger Menu Styling */
.mobile-menu-icon {
  display: none;
  cursor: pointer;
}

.hamburger {
  width: 30px;
  height: 22px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  z-index: 1001;
}

.hamburger span {
  width: 100%;
  height: 4px;
  background: #fff;
  border-radius: 5px;
  transition: all 0.4s ease;
}

.hamburger.active span:nth-child(1) {
  transform: rotate(45deg);
  top: 9px;
  position: absolute;
}

.hamburger.active span:nth-child(2) {
  opacity: 0;
}

.hamburger.active span:nth-child(3) {
  transform: rotate(-45deg);
  top: 9px;
  position: absolute;
}

/* Mobile Responsive Styling */
@media screen and (max-width: 768px) {
  .nav-links {
    display: none;
  }

  .nav-links-mobile {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 70px;
    right: 0;
    width: 100%;
    background-color: #000;
    z-index: 1000;
    animation: slideIn 0.5s ease forwards;
  }

  .nav-links-mobile li {
    margin: 20px 0;
  }

  .nav-link {
    font-size: 20px;
    padding: 10px 20px;
  }

  .mobile-menu-icon {
    display: block;
  }
}

/* Animations */
@keyframes slideIn {
  from {
    right: -100%;
  }
  to {
    right: 0;
  }
}

/* Content Styling */
.content {
  /* Adjust padding to create space 
     between navbar and content */
  padding: 80px 20px; 
  /* Slightly different background 
     to differentiate from navbar */
  background-color: #1a1a1a; 
  min-height: 100vh;
}

.content h1 {
  font-size: 36px;
  color: #ff9800;
  margin-bottom: 20px;
}

.content p {
  font-size: 18px;
  line-height: 1.6;
  color: #ccc;
}

Step 4: Integrating the Responsive Navbar Component

Now, our responsive navbar component is ready. To use it we need to import the component into the main application file i.e. 'App.js'. Include the below-mentioned code for integrating the responsive navbar component into your application.

import React from "react";
import Navbar from "./Navbar"; // Import the Navbar component

function App() {
  return (
    <div className="App">
        <Navbar/>
    </div>
  );
}

export default App;

Step 5: Starting the Application

Once our code is ready, we need to run the application for output. Now you can go to your VSCode editor terminal and write the following command then run the application as shown below, In this repository, the app is running on port http://localhost:3000/.

npm start

Output

The output for the above-mentioned code for the responsive navbar is given below. Please note that the output is added in the form of a GIF. 

Conclusion

In this article, we made an attractive and responsive navbar with ReactJS. Alright, so we just had the basic structure and further added styling to it with some advanced CSS concepts for all this going to be visually amazing as well responsive in every device.

Updated on: 2024-08-26T10:53:15+05:30

0 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements