The navigation bar triggers the opening of all icon menus in their designated positions at the same time

This code snippet represents the navigation bar for an admin user, featuring 3 icons: navigation menu, user menu, and manage button icons. The problem arises when clicking on any of these icons, as all dropdown items from each icon are displayed in their respective locations. The desired behavior is to display the selected information for each specific icon.

  function NavbarAdmin() {
  const classes = navbarStyle();
  const [anchorEl, setAnchorEl] = React.useState(null);
  const isNavMenuOpen = Boolean(anchorEl);
  const isProfileMenuOpen = Boolean(anchorEl);
  const isManageMenuOpen = Boolean(anchorEl);

  const handleProfileMenuOpen = (event) => {
    setAnchorEl('profileMenu');
  };

  const handleNavMenuOpen = (event) => {
    setAnchorEl('navMenu');
  };

  const handleManageMenuOpen = (event) => {
    setAnchorEl('manageMenu');
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const userMenu = (
    <Menu
      anchorEl={'profileMenu'}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      keepMounted
      transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      open={isProfileMenuOpen}
      onClose={handleMenuClose}
    >
      <MenuItem onClick={handleMenuClose}>Profile</MenuItem>
      <MenuItem onClick={handleMenuClose}>My account</MenuItem>
      <MenuItem onClick={handleMenuClose}>Sign Out</MenuItem>
    </Menu>
  );

  const navMenu = (
    <Menu
    anchorEl={'navMenu'}
    anchorOrigin={{ vertical: 'top', horizontal: 'left' }}
    keepMounted
    transformOrigin={{ vertical: 'top', horizontal: 'left' }}
    open={isNavMenuOpen}
    onClose={handleMenuClose}
  >
    <MenuItem onClick={handleMenuClose}>Home</MenuItem>
    <MenuItem onClick={handleMenuClose}>Movies</MenuItem>
    <MenuItem onClick={handleMenuClose}>Concessions</MenuItem>
    <MenuItem onClick={handleMenuClose}>Showtimes</MenuItem>
  </Menu>
  );

  const manageMenu = (
    <Menu
    anchorEl={'manageMenu'}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
    keepMounted
    transformOrigin={{ vertical: 'top', horizontal: 'right' }}
    open={isManageMenuOpen}
    onClose={handleMenuClose}
  >
    <MenuItem onClick={handleMenuClose}>Movies</MenuItem>
    <MenuItem onClick={handleMenuClose}>Seats</MenuItem>
    <MenuItem onClick={handleMenuClose}>Test</MenuItem>
    <MenuItem onClick={handleMenuClose}>Test</MenuItem>
    <MenuItem onClick={handleMenuClose}>Test</MenuItem>
    <MenuItem onClick={handleMenuClose}>Test</MenuItem>
  </Menu>
  );

return (
    <div className={classes.grow}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start" className={classes.menuButton}
            color="inherit"
            aria-label="nav account"
            aria-haspopup="true"
            onClick={handleNavMenuOpen}
            color="inherit"
          >
            <MenuIcon />
          </IconButton>
          <Typography className={classes.acptheater} variant="h6" noWrap>
            ACP Theater
          </Typography>
          <div className={classes.grow} />
          <div>
            <IconButton aria-label="show messages" color="inherit">
              <Badge badgeContent={1} color="secondary">
                <MailIcon />
              </Badge>
            </IconButton>
            <IconButton
              edge="end" className={classes.menuButton}
              aria-label="user account"
              aria-haspopup="true"
              onClick={handleProfileMenuOpen}
              color="inherit"
            >
              <AccountCircle />
            </IconButton>
            <Button 
              edge="end" className={classes.menuButton}
              aria-label="user account"
              aria-haspopup="true"
              onClick={handleManageMenuOpen}
              color="inherit"color="inherit"
            >
                Manage</Button>
            <Button color="inherit">Login</Button>
          </div>
        </Toolbar>
      </AppBar>
      {manageMenu}
      {navMenu}
      {userMenu}
    </div>
  );
}

Answer №1

anchorEl holds the name of the menu that was clicked on. It is a string and cannot be converted to a Boolean value.

Therefore, you should check the variable that stores the name of the menu to be opened (let's refer to it as the "activeMenu"). (I've changed the variable from anchorEl to activeMenu to avoid conflicts with Material-UI attributes)

Something like this (please note that this code is untested, but follows the general principle):

const [activeMenu, setActiveMenu] = React.useState(null);

const handleProfileMenuOpen = (event) => {
    setActiveMenu('profileMenu');
};
const handleNavMenuOpen = (event) => {
    setActiveMenu('navMenu');
};
const handleManageMenuOpen = (event) => {
    setActiveMenu('manageMenu');
};
const handleMenuClose = () => {
    setActiveMenu(null);
};

Then, in the return statement:

return (
    // Your other code...

    {activeMenu === 'profileMenu' && (
        <Menu
          anchorEl={'profileMenu'}
          anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
          keepMounted
          transformOrigin={{ vertical: 'top', horizontal: 'right' }}
          open={isMenuOpen}
          onClose={handleMenuClose}
        >
          <MenuItem onClick={handleMenuClose}>Profile</MenuItem>
          <MenuItem onClick={handleMenuClose}>My account</MenuItem>
          <MenuItem onClick={handleMenuClose}>Sign Out</MenuItem>
        </Menu>

    )}
    {activeMenu === 'navMenu' && (
        <Menu
        anchorEl={'navMenu'}
        anchorOrigin={{ vertical: 'top', horizontal: 'left' }}
        keepMounted
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        open={isMenuOpen}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={handleMenuClose}>Home</MenuItem>
        <MenuItem onClick={handleMenuClose}>Movies</MenuItem>
        <MenuItem onClick={handleMenuClose}>Concessions</MenuItem>
        <MenuItem onClick={handleMenuClose}>Showtimes</MenuItem>
      </Menu>

    )}
)

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

Different ways to display an HTML page in a well by utilizing a div tag and jQuery from a side menu

Check out my Tutorial Page! Currently, I am working on a simple tutorial page utilizing bootstrap 3. My goal is to showcase the HTML file content within the well container on the right side of the page. However, I am facing challenges as I do not want to ...

Can Jquery be utilized to signal a language change?

I'm working on my portfolio website that will be available in two languages, Thai and English. I have successfully implemented language buttons for changing between the two languages. However, I am facing an issue with the language selection when nav ...

Navigation Menu Dropdown Present on the Right Side and Arranged in a Horizontal Stack

I'm having trouble with a dropdown menu in my navigation bar. I followed the example on W3Schools but when I hover, the menu appears horizontally instead of vertically and to the far right of the page. I've searched for solutions but can't s ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Customize the default getstream component styles in a NextJS Component

Is there a way to customize the CSS of getStream.io components using custom CSS? I have created a component as shown below and now I want to override the styles for various classes of its components. Following the instructions in this README file, I impor ...

Having trouble aligning material-ui GridList in the center

I am currently working with a GridList in order to display Cards. The styling for these components is set up as shown below: card.js const useStyles = makeStyles({ card: { maxWidth: 240, margin: 10 }, media: { heigh ...

Using Jest and React: How can I invoke a function within the expect(setInterval).toHaveBeenLastCalledWith() method?

While testing the component in the Jest environment, I am facing a challenge with passing the function callback inside the setInterval method. Every time I run the test, I encounter an error message related to the 'expect' statement: The mock ...

Can you answer this straightforward query about CSS positioning?

I am currently facing a challenge in creating a small div (header class) that overlays a main banner image div (banner class). When I maximize my browser window, the positioning is correct. However, upon resizing the browser, the header div maintains its m ...

Can anyone help me with displaying auto complete HTML files in VScode?

As a Korean, please excuse my lack of proficiency in English. This image displays the autocomplete feature for HTML files in IntelliJ. This particular file was generated by Spring Boot (start.spring.io). How can I achieve the same in VSCode? ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Adding a script to the head of a Next.js page by using the Script component

I need assistance with inserting tracking code from Zoho application into the Head section of each page in my Next.js application. I am currently using a _document.tsx file and following the instructions provided by Next.js regarding the use of the Next.js ...

Learn how to integrate a column link in a material-ui table that will redirect users to a detailed summary page based on the unique id of

Currently, I am utilizing Material-UI tables in my project and have added an id column to the basic table available here. If I have a page with this basic table example located at localhost:3000/basic-table within my React application, how can I transform ...

Learn the process of using calc to rotate images on hover with CSS and Jquery

Is there a way to implement the rotate on hover function for images, similar to what is seen on this website under 'our Latest Publications'? I attempted using calc and skew, however, I was unsuccessful in achieving the desired hovering effect o ...

Presenting XML data in HTML using a customized CSS stylesheet

I've explored various methods for showcasing an XML file on a web page using HTML, but I haven't yet encountered one that incorporates a CSS style sheet. The XML file I have already includes a CSS style sheet. When viewed in a web browser, the . ...

Using Jquery and AJAX to insert a PHP file into a DIV container

I am facing a challenge where I need to dynamically load a PHP file into a DIV element upon clicking a button, all without the page having to reload. If you refer to the 'Jsfiddle' document linked below, you will find further details and explana ...

Implement a captivating hover effect on every single element within a particular class

I created a basic website with the following design: However, there is an issue with the hover effect. It only works on the specific area where the mouse pointer is located (here ipsum). My intention was for the hover effect to work on all elements. To fi ...

D3 not distinguishing between bars with identical data even when a key function is implemented

When attempting to create a Bar chart with mouseover and mouseout events on the bars using scaleBand(), I encountered an issue. After reviewing the solution here, which explains how ordinal scale treats repeated values as the same, I added a key to the dat ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Eliminate the gaps between the columns of the table

Is there a way to eliminate the gap between the day, month, and year columns in this table? <form action='goServlet' method='POST'> <table style="width:1000px" style="text-align:center"> <tr style="text-ali ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...