Reputation: 321
Hey guys I really don't understand why is this happening. When I start the app, everything is okay. First item in menu has active class. But when I click on another item in menu, this item also receives this class active and previous class active has not been removed.
Picture for better understanding
HTML
<div className="menu">
<ul>
<li><NavLink to="/" activeClassName="active">Domov</NavLink></li>
<li><NavLink to="/about" activeClassName="active">O nás</NavLink></li>
<li><NavLink to="/portfolio" activeClassName="active">Portfólio</NavLink></li>
<li><NavLink to="/contact" activeClassName="active">Kontakt</NavLink></li>
</ul>
</div>
css
.menu ul{
list-style: none;
padding-left: 0;
li{
display: inline-block;
margin: 0 1.5em;
color: black;
font-weight: 400;
a{
color: black;
text-decoration: none;
&.active{
color:$mainColor;
}
}
}
}
What am I doing wrong?
Upvotes: 0
Views: 2387
Reputation: 3
In react-router-dom v6 you could also use the end
statement for your "/" route. In react-router-dom v6 you could also use activeStyle={{color: yourcolor}}
as a prop of the NavLink. I wasnt able to make the solution mentioned above work on the actual v6.
Upvotes: 0
Reputation: 4147
The reason is because even though you navigated to a new link the first link /
still evaluates as true.
You need to add exact
to your NavLink
s
<NavLink exact to="/portfolio" activeClassName="active">Portfólio</NavLink>
This will make sure the active class is only added if the route matches exactly as the to
link
Upvotes: 1