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

Chrome does not recognize the 'position: fixed' style attribute

Encountered an issue in Chrome where the position:fixed property does not behave as expected. While this code works fine in Firefox and Safari, it seems to have a glitch in Chrome (69.0.3497.100). When scrolling, the blue div moves and reveals the green ba ...

Can you tell me what this code on Facebook is for?

Upon inspection of Facebook's activity in my browser, I stumbled upon the following code snippet: for (;;);{"t":"refresh"} Attempting to decipher its purpose reveals an infinite loop. Can you identify its function? ...

Combining Turn.js with AJAX for an interactive web experience

I've been experimenting with turn.js and struggling to find an example of loading dynamic pages with content via ajax. While the page is loading, it's not displaying all the results. For a JSON result from the controller, click here. <div clas ...

Unable to interpret AJAX request using PHP

I am trying to implement a feature where file contents can be deleted upon the click of a button. I have set up an ajax request that sends two variables - the filename and the name of the person who initiated the deletion process. The PHP function is runni ...

Vertical alignment in material-ui's Grid component is not functioning as expected

I have been working on this code snippet to center a button both vertically and horizontally. However, it seems like the button is not positioned correctly along the vertical axis. Any advice or guidance would be greatly appreciated! Could someone assist ...

Tips for solving issues with dependencies in React applications

After running "npm install," I encountered the following errors in the console: elena@elena-dev:~/PROYECTO FINAL CTD/grupo-12/frontend/proyecto-integrador$ npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While reso ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Error message indicating that the host has been configured in both the settings() and useEmulator() functions for the Firebase Firestore emulator, therefore the emulator host will

Initially, I encountered the complete error message. @firebase/firestore: Firestore (8.1.1): Host has been set in both settings() and useEmulator(), emulator host will be used Error [FirebaseError]: Firestore has already been started and its settings c ...

Tips for updating the color scheme in your CSS file by making hue adjustments to all colors

I have a CSS file and I am looking to automatically generate multiple color variations of the file by altering the hue, similar to using the "colorize" function in GIMP. I came across a tool that does exactly what I need at , however it does not support t ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load. ...

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

Implementing pagination to streamline search result presentation

I am struggling to implement pagination for the following query that retrieves a lengthy list of items from the database. I want to limit the display to 10 items per page but unsure how to integrate pagination into the existing function. // fetching items ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...