0
votes

The pages:

  const pages = [
    {
      name: "aaa",
      section: ["1", "2", "3"],
    },
    {
      name: "bbb",
      section: ["1", "2"],
    },
    {
      name: "ccc",
      section: ["1", "2", "3", "4"],
    }
  ];

The returned component:

  return (
    <AppBar color="inherit">
      <Container maxWidth="xl">
        <Box sx={{ flexGrow: 1, display: { md: "flex" } }}>
          {pages.map((page) => (
            <Box>
              <Button
                key={page.name}
                onClick={handleOpenNavMenu}
                sx={{ my: 2, color: "gray", display: "block" }}
              >
                {page.name}
              </Button>
              <Menu
                sx={{ mt: "45px" }}
                key={page.name}
                anchorEl={anchorElNav}
                anchorOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                keepMounted
                transformOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                open={Boolean(anchorElNav)}
                onClose={handleCloseNavMenu}
              >
                {page.section.map((section) => (
                  <MenuItem key={section} onClick={handleCloseNavMenu}>
                    <Typography textAlign="center">{section}</Typography>
                  </MenuItem>
                ))}
              </Menu>
            </Box>
          ))}
        </Box>
      </Container>
    </AppBar>
  );
};

export default NavBar;

Is my double for-loop usage incorrect?

I would like to mount the specific section as menu to the respective button. However, the result turns out to be each button is mounted with all the menus and overlaying each other.

Current output:

| aaa | bbb | ccc |
  111   111   111
  222   222   222
  3 3   3 3   3 3
    4     4     4

Expected output:

| aaa | bbb | ccc |
   1     1     1
   2     2     2
   3           3
               4

I cannot spot the logical flaw in my code. Could anyone please help? Big thanks.

There's no flaw in this piece of code. The problem is occurring at the upper level. I've run this code out of curiosity, and it works as intended. Check There could be a problem in rendering the current component. You can upload the parent component if you want us to take a look - Ovi