'Style each navbar link according to current path

So I have a very simple navbar that contains 5 links:

 <div className='links' id={showLinks? "hidden": ""}>
        <a class="btn" href="/">Dashboard</a>
        <a class="btn" href="/tenants">Tenants</a>
        <a class="btn" href="/stores">Stores</a>
        <a class="btn" href="/pos">POS</a>
        <a class="btn" href="/Invoices">Invoices</a>
        </div>

It works however, I want to style the links based on which page I am on. For example, when I click on Stores, I want the Stores link in the navbar to be highlighted like in this image: Active Stores I know how to do the CSS to achieve this result, I just need to change the class name dynamically according to the link. I tried using useLocation in the Navbar but it only gets the location once, and not with each reload. If that makes sense.



Solution 1:[1]

Just maintain a state variable for active menu item and onClick handle the update.

const data = ["Dashboard", "Tenannts", "Stores"];
const Element = () => {
  const [activeMenu, setActiveMenu] = React.useState("");

  return (
    <div>
      {data.map((menu) => (
        <span
          key={menu}
          className={activeMenu === menu ? "active-btn" : "normal-btn"}
          onClick={() => setActiveMenu(menu)}
        >
          {menu}
        </span>
      ))}
    </div>
  );
};

const domContainer = document.querySelector("#app");
ReactDOM.render(<Element />, domContainer);
.normal-btn {
  color: black;
  margin: 0 10px;
}

.active-btn {
  color: black;
  margin: 0 10px;
  border-bottom: 2px solid blue;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"> </div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siva K V