How to make sub menus for nav link?

3.8k views Asked by At

Hi I am new to react and wanted to implement sub menus to my menu.

What I wanted was something like this Report > My report > MIS report

I am importing and using NavLink from react router dom.

The menu currently looks like this with no sub-menus:

This is my code where I am using the nav bar link:

export const mainListItems = (
  <List>
    <NavLink to="dashboard">
      <ListItem button>
        <ListItemIcon></ListItemIcon>
        <ListItemText primary="Dashboard" />
      </ListItem>
    </NavLink>
    <NavLink to="userform">
      <ListItem button>
        <ListItemIcon></ListItemIcon>
        <ListItemText primary="Registration" />
      </ListItem>
    </NavLink>
    <NavLink to="">
      <ListItem button>
        <ListItemIcon></ListItemIcon>
        <ListItemText primary="Report" />
      </ListItem>
    </NavLink>
  </List>
);
This is the link in my App.js

const App = () => (
  <HashRouter>
    <Switch>
      <Route path="/signin" component={SignIn} />
      <Route path="/userform" component={UserForm} />
      <Route path="/dashboard" component={Dashboard} />

      <Redirect from="/" to="signin" />
    </Switch>
  </HashRouter>
);
I need some direction in this. How do I implement my own sub menus
1

There are 1 answers

12
Giovanni Esposito On BEST ANSWER

Ciao, for nested navigation you could use ListItem and Collapse components from Material UI like this:

       <ListItem button onClick={this.handleClick}>  // Report level
          <ListItemIcon>
            <InboxIcon />
          </ListItemIcon>
          <ListItemText primary="Report" />
          {open ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={open} timeout="auto" unmountOnExit>  //first nested level
          <List component="div" disablePadding>
            <ListItem
              button
              style={styles.nested}
              onClick={this.handleClickSecondLevel}
            >
              <ListItemIcon>
                <StarBorder />
              </ListItemIcon>
              <ListItemText primary="My Report" />
              {openSecondLevel ? <ExpandLess /> : <ExpandMore />}
            </ListItem>
            <Collapse in={openSecondLevel} timeout="auto" unmountOnExit>  // second nested level
              <List component="div" disablePadding>
                <ListItem button style={styles.nestedSecondLevel}>
                  <ListItemIcon>
                    <StarBorder />
                  </ListItemIcon>
                  <ListItemText primary="MIS Report" />
                </ListItem>
              </List>
            </Collapse>
          </List>
        </Collapse>

Here a codesandbox example using class component.