How can I close the menu when a menu item is clicked in a React.js application?

I am facing an issue where I want to close the menu when clicking on any menu item in React JS. The functionality works fine with a button icon but not with individual menu items. How can I resolve this problem? I have been trying to implement it using CSS properties. Please refer to the screenshot below for more information.

Even though it works perfectly on button click, the menu does not close when clicking on a specific item.

https://i.sstatic.net/1IzYF.png

Code:

import Link from 'next/link'
import Image from 'next/image'
import navbar from '/const/navbar'
import Button from '../button'
import { useState } from 'react'

export default function Navbar() {
   const [activeClass, setActiveClass] = useState(0);

   return (
      <>
         <nav>
            <input id="nav-toggle" type="checkbox" />
            <div className="logo">
            <Link href="/">
            <Image className=" cursor-pointer h-8 opacity-90" src="/workforwin-logo.png" width={172} height={44} alt="Workforwin Logo" />
            </Link>
            </div>
               <ul className="links">
                  {/* Getting nav items */}
                  {navbar.data.map((items, i) => (
                     <li className={activeClass === i ? "text-indigo-600" : "hover:text-indigo-600"} key={i} onClick={() => setActiveClass(i)}><Link href={items.link}>{items.text}</Link></li>
                  ))}
                  {/* Account Button */}
                  <Button link="" data="Account" type="" />
               </ul>
            <label htmlFor="nav-toggle" className="icon-burger">
               <div className="line"></div>
               <div className="line"></div>
               <div className="line"></div>
            </label>
         </nav>
      </>
   )
}

CSS:

nav {
    position: fixed;
    z-index: 10;
    left: 0;
    right: 0;
    top: 0;
    padding: 0 4%;
    height: 60px;
    background-color: var(--secondary);
    display: flex;
    justify-content: space-between;
    -webkit-box-shadow: 0px 0px 14px 0px rgba(0,0,0,0.2);
    -moz-box-shadow: 0px 0px 14px 0px rgba(0,0,0,0.2);
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.2);
    /* -webkit-border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px;
    -moz-border-bottom-left-radius: 5px;
    -moz-border-bottom-right-radius: 5px; */
}
nav .logo {
    float: left;
    width: 30%;
    height: 100%;
    display: flex;
    align-items: center;
    font-size: 28px;
    color: #e4d7d5;
    /* font-family: 'Courier New', Courier, monospace; */
}

nav .links {
    /* float: right; */
    padding: 0;
    margin: 0;
    width: 70%;
    height: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
nav .links li {
    list-style: none;
    /* color: var(--text-primary); */
    transition-delay: .1s;
  transition-duration: 1s;
}
nav .links li:hover{
  /* color: var(--text-secondary); */
  transition-delay: .1s;
  transition-duration: 1s;
}
nav .links a {
    font-size: 16px;
    font-weight: 600;
    /* color: #603030; */
    text-decoration: none;
  padding: 10px 15px;
    text-transform: uppercase;
    text-align: center;
    display: block;
}

#nav-toggle {
    position: absolute;
    top: -100px;
}
nav .icon-burger {
    display: none;
    position: absolute;
    right: 5%;
    top: 50%;
    transform: translateY(-50%);
}
nav .icon-burger .line {
    width: 25px;
    height: 4px;
    background-color: var(--skyblue);
    margin: 5px;
    border-radius: 3px;
    transition: all .3s ease-in-out;
}

.btn-class{
    text-decoration: none !important;
}

Answer №1

// The following is the JavaScript script section
const [isOpen, setIsOpen] = useState(false);

const openMenu = () => {
    setIsOpen(true);
}

const closeMenu = () => {
    setIsOpen(false);
} 
// Here is the JSX part for rendering the menu
<div className={ isOpen ? 'menuIcon open':'menuIcon'}>
    <ul className='navbar-list'>
        <li>
            <NavLink className="navbar-link" to='/' onClick={closeMenu}>Home</NavLink>
        </li>
        <li>
            <NavLink className="navbar-link" to='/about' onClick={closeMenu}>About</NavLink>
        </li>
        <li>
            <NavLink className="navbar-link" to='/services' onClick={closeMenu}>Services</NavLink>
        </li>
        <li>
            <NavLink className="navbar-link" to='/contact' onClick={closeMenu}>Contact</NavLink>
        </li>
    </ul>
    <div className="mobile-navbar-btn">
        <CgMenuMotion name="menu-outline" className='mobile-nav-icon' onClick={openMenu} />
        <CgCloseR name="close-outline" className='mobile-nav-icon close-outline' onClick={closeMenu} />
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying an image in AngularJS using a byte array received in the response

Dealing with a service that adds properties to a file and returns it as a byte array in the response. I'm struggling to display it properly since it's in byte form. Attempted converting it to base64 but still showing raw bytes. PNG IHDR&L ...

What is causing my nested class to be treated as a sibling rather than a child in HTML code

I have been searching for a clear answer to my query, but haven't found one yet. In my HTML script, I have nested divs structured like this: <ul id="navbar"> <li><a href='#' class='dropdown'>Rules</a> ...

What is the best way to connect an event in Angular 2?

This is an input label. <input type="text" (blur) = "obj.action"/> The obj is an object from the corresponding component, obj.action = preCheck($event). A function in the same component, preCheck(input: any) { code ....}, is being used. Will it wor ...

npm unable to locate the specified file

I'm currently following a tutorial on creating a Google Maps clone. After completing the build, I tried running the npm start command but encountered the following errors: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\m ...

Tips for implementing custom string ordering with Sequelize

Seeking guidance on implementing custom order with Sequelize I'm attempting to organize an array of objects fetched from the database as ACTIVE, PENDING, INACTIVE Any suggestions or examples for accomplishing this using Sequelize? Attempted approac ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

Using Material-UI to programatically select text in a TextField

Welcome to Material-UI V1 beta. I couldn't seem to locate the answer in the documentation. Can someone help me understand how to select text of a TextField component? ...

When you hover, there is no writing cursor in sight

I'm looking for a way to display a label on an input field and have a writing cursor show up when hovering over the label. I am not interested in using a placeholder label. Do you have any simple solutions for this? See the code snippet below: JSFiddl ...

How to generate flexible arrays using an established array?

Currently, I am working on creating a new array from an existing one. The structure of my current array is outlined below. How can I ensure that adding a new object results in a new array starting from that point? myArray: [{ anima ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

Guide on implementing register helpers with node.js and express handlebars

When loading a record, I have a select option on my form and want to pre-select the saved option. Here is the code: The Student.hbs file displays the form, with the act obj coming from the student.js route student.hbs <form> <div class="for ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

What is a unique method for creating a wireframe that replicates the structure of a square grid without using interconnected nodes

Currently, I am in the process of designing the wire frame styles for human body OBJs and my goal is to achieve a wire frame similar to the image below. In the following lines, you will find the code snippets that illustrate how I create the wire frame alo ...

What is the process for invoking a JavaScript function and storing form data in a text file within an HTML document?

My HTML code is here..... <!DOCTYPE html> <html> <title>Plot</title> <head> <script type="text/javascript" src="d3.min.js"></script> <script> function filter() { var choice = document.ge ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

npm: generate new script directive

When I start up my NodeJs (ES6) project, I usually enter the following command in the console: ./node_modules/babel/bin/babel-node.js index.js However, I wanted to streamline this process by adding the command to the scripts section of my package.json fi ...

Incorporating a function from a separate .js file into an index.ejs view using app.js

graphs.js: contains a function that initiates an API call and retrieves an object containing an HTML link for embedding a graph. app.js: includes the following (graphs.js has been imported): var express = require("express"); var app = express(); var grap ...

What methods can be used to initiate form error handling in React/Javascript?

I am currently utilizing Material-UI Google Autocomplete, which can be found at https://material-ui.com/components/autocomplete/#google-maps-place, in order to prompt users to provide their address. https://i.stack.imgur.com/nsBpE.png My primary inquiry ...

Why does CSS respect height:auto for relative positioned parent elements but not width:auto?

Although CSS position properties may seem simple at first, when building a layout, tons of weird edge cases can come out of nowhere. One thing that I always overlooked was using height: auto or width: auto. To gain a better understanding, I stumbled upon ...

Sending an array to another file upon button click event in a React application

Hey everyone, I'm currently getting started with React. I have this interesting situation where I need to handle an array of IDs that are obtained from selected checkboxes. My goal is to pass this array to another file called Employee.js when a button ...