Dynamic material ui drop menu

Viewed 541

I am creating a drop menu dynamic using material-ui js, but when i click on one of the menu it opens all the menu and vice versa when close it.

code

1 Answers

You are maintaining 1 state for both the menu links. Maintain a name(page.title) for your list. In the handlerListOpen function dynamically set/toggle the state object using key.

Working copy of your codesandbox

Code Snippet:

export default function App() {
  const [openList, setopenList] = React.useState({});

  const handlerListOpen = el => {
    console.log("el", el.currentTarget.getAttribute("name"));
    const target = el.currentTarget;
    setopenList(prev => ({
      ...prev,
      [target.getAttribute("name")]: !prev[
        target.getAttribute("name")
      ]
    }));
  };
  return (
    <List component={"nav"}>
      {pages.map((page, index) => (
        <List>
          <ListItem name={page.title} button onClick={handlerListOpen}>
            <ListItemIcon>{pages.icon}</ListItemIcon>
            <ListItemText primary={page.title} />
            {openList[page.title] ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          {page.collapse.map((collapse, index) => (
            <Collapse in={openList[page.title]} timeout="auto" unmountOnExit>
              <li>
                {" "}
                <Link to={collapse.href}>
                  <List component="div" disablePadding key={index}>
                    <ListItem button>
                      <ListItemIcon>{collapse.icon}</ListItemIcon>
                      <ListItemText primary={collapse.title} />
                      <ListItemIcon>
                        <ChevronRightIcon />
                      </ListItemIcon>
                    </ListItem>
                  </List>
                </Link>
              </li>
            </Collapse>
          ))}
        </List>
      ))}
    </List>
  );
}
Related