automatically collapse a submenu once a different menu option is selected

After doing some research and trying out various solutions, I still couldn't get it to work. I made adjustments to my dropdown menu and click function so that each submenu opens and closes when its parent is clicked. However, I'm now looking to figure out how to close an open submenu when a different menu is clicked, as currently they all stack up on the menu bar. Any guidance on how I can achieve this would be greatly appreciated. Thank you for your help.

I am working with next js.

 <div
      className={ classNames(classes.root, {
        [classes.rootActive]: active ,
        [classes.rootExpanded]: isMenuShrunk,
     
      })}
      ref={anchor}
      onClick={event => handleClick(event, menuItem) }

    >
      <button
        className={classes.menuItemBtn}
        data-test="menu-item-label"
        data-test-id={menuItem.testingContextId}
      >
        {menuItem.iconSrc && <div className={classNames(classes.icon, {
            [classes.icon]: isMenuShrunk
          })} > <SVG src={menuItem.iconSrc}/></div>}
        <Typography
          aria-label={menuItem.ariaLabel}
          className={classNames(classes.label, {
            [classes.hideLabel]: !isMenuShrunk
          })}
          variant="body2"
        >
          {menuItem.label}
        </Typography>
      </button>
      {menuItem.children && (
        <Collapse
         timeout="auto"
         unmountOnExit
         className={classNames({[classes.popper]: open && isMenuShrunk,})}
         in={open}
        >
      
            <div>
              {menuItem.children.map(subMenuItem => (
                <Typography
                  aria-label={subMenuItem.ariaLabel}
                  component="button"
                  className={classNames({[classes.subColor]:!color , [classes.subMenuLabel]:open||!open,
                      [classes.sublabel]:open||!open})}
                  key={subMenuItem.url}
                  onClick={event => handleClickSubMenu(event, subMenuItem)}
                  data-test="submenu-item-label"
                  data-test-id={subMenuItem.testingContextId}
                  variant="body2"
                >
                  {subMenuItem.label}
                </Typography>
              ))}
            </div>
        </Collapse>
      )}
    </div>

Answer №1

Potential Solutions

Option 1

To enhance functionality, consider converting the open state from boolean to string format, moving it to the root level, and storing the opened menu id within it. Adjust the open condition as follows: open==='menuId'. This modification allows for displaying only one active menu at a time.

Option 2

An alternative approach is to utilize the context API to envelop the entire menu, granting control over the state directly from the context.

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

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...

Why is my mock function not being invoked within an 'if' statement in my React app testing with jest and enzyme?

Currently, I am encountering an issue while writing a test case for my react app. The problem arises when attempting to simulate a button click with a mock function. Even though I pass the mock function as a prop and call it inside an 'if' statem ...

Exploring the Various Textures within the CANVAS 2D Context

Exploring new techniques for filling the canvas, I am currently trying to add texture to an object similar to the blobs from the blob example (http://www.blobsallad.se/). The challenge is that the current example is utilizing the 2D context without webGL i ...

Get the selected row value from a Table and convert it into an array. Then, pass this array as a parameter to another function

I need help with logging and storing selected values from a Table component in React My Table component displays data from an API with checkboxes on each row. I'm using the <Table /> Material UI component for React. The documentation states th ...

How can we create responsive websites?

Since starting my Software Developer studies about 3 months ago, I've been working on a website project for a driving school with a team of four. The issue we're facing is that when we transfer and open files between laptops, the website layout a ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { id: 1, first_name: "Mikkel&qu ...

Querying Denormalized Data in AngularFire 0.82: Best Practices and Strategies

I have a question that is related to querying denormalized data with AngularFire. I am looking for a solution specifically using AngularFire (current version 0.82). Here is an example of the data structure I am working with: { "users": { "user1": { ...

Issue with Bootstrap modal not closing automatically after submitting an ajax form

I am facing an issue with a modal on my page that is used for submitting courses registered by students. Even after successful submission, the modal closes but leaves behind a faded background. I have attempted various solutions from StackOverflow without ...

What causes the image to vanish once the CSS animation is activated?

Is there a reason why the image disappears after the animation completes? :/ .coin { width: 200px; height: 200px; background-size: cover; animation: CoinflipRoll 6s steps(199); animation-delay: .5s; animation-fill-mode: forwards; ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Monitor the incoming POST request

Is there a way to monitor incoming post requests in a form? I have the following form: <form method='post'> <input type='text' name'test' /> <input type='submit' name'submit' /> </for ...

When an express pre-remove signal initiates another pre-remove action during the removal process

Imagine having 4 different models structured like this: ┌────────────┐ ┌────────────┐ │ User │ │ Goal │ ├────────────┤ 1 ├───── ...

How can I reverse a regex replace for sentences starting with a tab in JavaScript?

In order to format the text properly, I need to ensure that all sentences begin with only one Tab [key \t] and remove any additional tabs. input This is aciton Two tab One tabdialog This is aciton Two tab Second tabdialog out ...

Adjusting the label on the Formik toggler

I have successfully implemented a switcher using Formik that changes the label accordingly with a boolean value. However, I now need to make the label reflect a string value instead of just "true/false." For example, I want it to display "Text1/Text2" inst ...

In my Flask Bootstrap website, the navigation bar remains unchanged by the presence of Javascript

I am currently in the process of creating a navigation bar for my Flask website using Bootstrap. However, when I implemented it into my HTML code, it is not displaying correctly which leads me to believe that the JavaScript may not be functioning properly. ...

Is it possible for me to invoke an anonymous self-executing function from a separate scope?

I'm having an issue with calling the hello() function in ReactJS. When I try to call it, I receive an error message that says "Uncaught ReferenceError: hello is not defined". How can I go about resolving this error? This is a snippet from my index.ht ...

Creating a transparent background for a Canvas animation with three.js and dat.gui

I'm struggling to set up a background animation on this canvas using three.js. However, the background renders as black instead of transparent. I attempted to adjust it with CSS by adding background-color:transparent;, but to no avail. I've searc ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

I am experiencing issues with the react function withRouter not working correctly. How can I resolve this in the latest version?

I've exhausted every possible solution to get it working, yet I find myself stuck in the same spot. How can I bypass this issue? Why isn't it functioning correctly? import React, { useEffect, useState } from "react"; import { withR ...