Skip to content
Advertisement

How to make an active navbar link when it shows its page using react-bootstrap

I’m using react bootstrap and react in the development of my portfolio app, however, I just need one small detail to add and can’t find the right method to do it.

I need to make the link on the navbar switch color depending on the page, for instance if I’m on the home page, “Home” on the navbar should be different in color, and so on.

This is the last thing i need to finalize my code.

if you want to check the whole repository here it is: https://github.com/awadbilal/portfolio

This is my navbar code:

JavaScript

And here is how it should look:

enter image description here

Advertisement

Answer

Import the useLocation hook from React Router then you can make some dynamic classNames:

JavaScript

And so on. Do this for each Link and add the path name, and it’ll work like expected.

Obviously in your CSS you need to create a class to show the active link, e.g.:

JavaScript

Update

Now with React Router 6’s <NavLink> component, you can easily implement this by reading the isActive argument passed to a function inside the className prop:

JavaScript

This makes our works a lot more flexible and not hard-coded.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement