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>