Change collapse behavior of drawer

Auto hide the drawer on click of a nav item

The current behavior of the drawer is that when you click outside the drawer then only it collapses. But sometimes you might need to collapse the drawer soon you click the nav item inside of that drawer.

Following the below steps you can easily achieve this:

In the NavMenuItem component, use the setSidebarOpen function from LayoutContext with following line of code:

const { setSidebarOpen } = useContext(LayoutContext);

Now, in the return statement of NavMenuItem component, On the component, you can put the onClick prop and bind that with a function which sets the sidebarOpen context value to false as shown in the following line of code:

return (
  <List component="div" className={clsx(classes.navMenuItem, 'Cmt-nav-menu-item')} 
    onClick={() => setSidebarOpen(false)}>
    <NavLink className={clsx(classes.navMenuLink, 'Cmt-nav-menu-link')} to={link}>
      {/* Display an icon if any */}
      {renderIcon()}
      <span className={clsx(classes.navText, 'Cmt-nav-text')}>{name}</span>
    </NavLink>
  </List>
);

Thats all you need to do to make drawer collapse on click of a nav item.

Last updated