Tackle navigation active link obstacle

Hi,

Building a React app atm. I’m trying to create an active link feature for the page you are on… so for example if you’re on /customers the location.pathname will say /customers and if it matches the route it will return true and Customers will be in bold.

Now i also have /customers/edit/ID and /customers/new but as of right now when you are on those pages the Customers link isn’t in bold. I’m trying to change that but i can’t figure out the logic so any help in achieving this would be much appreciated.

Right now i think i just need anything after the route to be replaced with nothing so /customers/new or /customers/new/ becomes just /customers but then by doing it that way it would activate the dashboard link even though i’m not on that page. That’s the obstacle. All help appreciated. Thanks

The code below is the simple bit where if you’re on /customers and it all matches then it’s gonna be bold.

Logic:

  const navigate = useNavigate();
  const location = useLocation();

  const pathMatchRoute = (route) => {
    if (route === location.pathname) {
      return true;
    }
};

Return:

<li onClick={() => navigate("/")}>
          <span className={pathMatchRoute("/") ? "bold" : ""}>Dashboard</span>
        </li>
        <li onClick={() => navigate("/invoices")}>
          <span className={pathMatchRoute("/invoices") ? "bold" : ""}>
            Invoices
          </span>
        </li>
        <li onClick={() => navigate("/customers")}>
          <span className={pathMatchRoute("/customers") ? "bold" : ""}>
            Customers
          </span>
        </li>

if everything you’re trying to highlight is a single depth…split on / and take only the 1’th (note: not 1st, 1’th.) item in the resultant array for comparison?

I’m confused about what you want, tbh.

This reads as “if pathname === route, make it bold”.

…why? What are you going to do with that information?

Which is true. So… why did you need to trim off the other stuff?

These two statements are opposing each other. Do you want it bold, or not?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.