Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get Material-UI Drawer to highlight the page it is currently at?

I'm currently trying to implement a website using Material-UI's drawer component. It works, when I click on the Drawer Items, it routes me to the correct pages.
But how do I get the individual Drawer Items to highlight the current page it is on.

For instance, if I am on /dashboard page, and if the Drawer Item for Dashboard page should be highlighted (different color and styles) to indicate that I am currently on that page dynamically.
Haven't manage to find any good solutions online and the Material-UI docs doesn't have a demo of how this is possible, great to hear how you all do it.

like image 553
Daryll Avatar asked Oct 22 '25 23:10

Daryll


1 Answers

You can highlight the current ListItem in the Drawer by setting selected props to true and use the pathname information to determine if the item matches the current route:

const routes = {
  Home: "/",
  About: "/about",
  Users: "/users"
};
const { pathname } = useLocation();
<List>
  {Object.keys(routes).map((routeName, index) => {
    const route = routes[routeName];

    return (
      <ListItem selected={route === pathname} button key={route}>
        <ListItemText primary={routeName} />
      </ListItem>
    );
  })}
</List>

Live Demo

Edit 67026979/how-do-you-get-material-ui-drawer-to-highlight-the-page-it-is-currently-at

like image 96
NearHuscarl Avatar answered Oct 24 '25 13:10

NearHuscarl