Resolving My Navlink active class Issue in React-router-v6
If you're using React-router-v6, you may have encountered an issue where the active
class is not being applied to the NavLink
component as expected. This can be frustrating, especially if you're trying to style your navigation links based on their active state.
The good news is that there is a simple solution to this issue. In React-router-v6, the active
class is now applied to the NavLink
component based on the isActive
prop. This prop is a boolean value that indicates whether or not the NavLink
is currently active.
To use the isActive
prop, you need to first import it from the react-router-dom
package. You can do this by adding the following line to your code:
import { NavLink, useLocation } from "react-router-dom";
Once you've imported the isActive
prop, you can use it in your NavLink
component like this:
Home
This will apply the active
class to the NavLink
component when the user is on the home page.
You can also use the isActive
prop to conditionally render content based on the active state of the NavLink
component. For example, you could use the following code to render a different icon for the active link:
const NavLinkIcon = ({ isActive }) => { return isActive ? ★ : ☐; };Home
This code will render a filled-in star icon for the active link and an empty star icon for the inactive links.
With these simple changes, you can easily resolve the issue with the active
class in React-router-v6.