Data Analyse Breda

React JS & MUI: Creating a Navbar with Conditional Menu Items

In this blogpost we will show you how you can create a React navbar with menu items that are displayed based on the url of the application.

As you can see in the video below (and sandbox at the bottom of the post) we have a Navbar where the last item changes based on the url. If the url contains page A menu A is shown, if the url contains page B than we display menu B.

The full code is available in a sandbox included in the end of this post. I

Why would you want conditional menu items?

Often an application has multiple user groups or modules, which each need to see different items on the navbar within your application.

By creating multiple menus and showing them conditionally you can provide the users with the links relevant to their module or user group.

I am not going to discuss the ful Navbar code, but it is all included in the sandbox. For the Navbar I used Material UI components, so make sure to install these dependencies when

Creating our conditional logic

So let’s discuss the logic of showing a menu based on the url of the webapp. In order to do this we need to the following things:

  • Give the urls that need to show the same Menu a similar name. In this example I have some urls including the name PageA, and some urls named Page B. We are going to make sure that different menus are going to show up, depending on these url names.
import "./styles.css";
import Navbar from "./Navbar";
import ContentHolder from "./Contentholder";
import { Route, Routes } from "react-router-dom";
import PageA from "./Pages/PageA";
import PageAunique from "./Pages/PageAunique";
import PageB from "./Pages/PageB";
import PageBunique from "./Pages/PageBunique";

export default function App() {
  return (
    <div className="App">
      <Navbar />
      <ContentHolder>
        <Routes>
          <Route path="/PageA" element={<PageA />} />
          <Route path="/PageA/unique" element={<PageAunique />} />

          <Route path="/PageB/" element={<PageB />} />
          <Route path="/PageB/unique" element={<PageBunique />} />
        </Routes>
      </ContentHolder>
    </div>
  );
}

I am not going to touch upon the Navbar code but it is available in the sandbox. The React Navbar is build up with Material UI components, so make sure to install all relevant dependencies.

  • Create different Menus for each url name you create (in our case PageA and PageB). I have created a menu called MenuA and MenuB. The first two menu-items are the same, the third menu-item is different.
import * as React from "react";
import { Link, useLocation } from "react-router-dom";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import HomeIcon from "@mui/icons-material/Home";
import PersonIcon from "@mui/icons-material/Person";
import StarIcon from "@mui/icons-material/Star";

export default function MenuB() {
  const location = useLocation();
  const path = location.pathname;
  return (
    <List>
      <ListItem
        component={Link}
        to="/PageA"
        button
        key={"1"}
        selected={"/PageA" === path}
      >
        <ListItemIcon>
          <HomeIcon />
        </ListItemIcon>
        <ListItemText primary={"Page A"} />
      </ListItem>

      <ListItem
        component={Link}
        to="/PageB"
        button
        key={"2"}
        selected={"/PageB" === path}
      >
        <ListItemIcon>
          <PersonIcon />
        </ListItemIcon>
        <ListItemText primary={"Page B"} />
      </ListItem>

      <ListItem
        component={Link}
        to="/PageB/unique"
        button
        key={"3"}
        selected={"/PageB/unique" === path}
      >
        <ListItemIcon>
          <StarIcon />
        </ListItemIcon>
        <ListItemText primary={"Page B unique"} />
      </ListItem>
    </List>
  );
}
  • Now we create the logic in our Navbar file which will show the correct Menu based on the active url. To do this we need to use the useState. useLocation, and useEffect (React) Hooks.
...
const [thedrawer, setThedrawer] = useState(<MenuA />);
  const location = useLocation();

  useEffect(() => {
    if (location.pathname.indexOf("PageA") > -1) {
      setThedrawer(<MenuA />);
    }

    if (location.pathname.indexOf("PageB") > -1) {
      setThedrawer(<MenuB />);
    }
  }, [location.pathname]);
...

How does this logic work?

  • First, we create a useState constant named thedrawer, where we specify that the default state should use MenuA.
  • Second, we use useLocation to create a constant that gives us the url of the webpage the users is currently on.
  • In the useEffect hook we create two if statements. If the url name contains PageA we change the thedrawer constant to MenuA. If the url name contains PageB the menu is changed to MenuB.
  • Very important, we specify the location.pathname in brackets after our if statements. This makes sure that the if statements are triggered every time the url changes. So every time we switch page, the code checks whether the menu view should be changed.

That’s how you create a conditional menu in React!

I hope this post has helped you to create a conditional menu in your React application. The full code is available in the Sandbox below.

You can also add conditional logic in your menu file, avoiding the creation of multiple menus. However, when the menus differ a lot it is easier to just create seperate menu files.

This example is hard coded. If you have a big application that it changing a lot it is better to find a more dynamic way to solve this. Perhaps by storing the structure of the menus and the permissions per group in your database.

This example is hard coded. If you want to include a lot of conditional logic it is better to find a more dynamic approach, perhaps storing the structure in your database.

Leave a Reply