Reputation: 6936
I am creating basic routing in react-router-5
<Router>
<div>
<Navbar />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
And in navbar.js like this
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="/home">
Good Site
</a>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<NavLink
className="nav-link"
to="/"
activeClassName="active-link"
>
Home
</NavLink>
</li>
<li className="nav-item">
<NavLink
className="nav-link"
to="/about"
activeClassName="active-link"
>
About
</NavLink>
</li>
<li className="nav-item">
<NavLink
className="nav-link"
to="/contact"
activeClassName="active-link"
>
Contact
</NavLink>
</li>
</ul>
</div>
</nav>
the problem i am facing is that the home route always have active-link
class. What i am doing wrong here? Please help.
Upvotes: 0
Views: 269
Reputation: 15499
This is occuring becuse of all other routes have the "/" as part of them - so it is being selected as a part of any other selected NavLink.
If you put exact
in your NavLink as well as in the Route - it should resolve the problem since the route now will only match the selected route link and if the user is not selecting a route then the home page will be selected via the "/" route link.
...
<li className="nav-item">
<NavLink
className="nav-link"
exact to="/"
activeClassName="active-link"
>
Home
</NavLink>
</li>
<li className="nav-item">
<NavLink
className="nav-link"
exact to="/about"
activeClassName="active-link"
>
About
</NavLink>
</li>
...
Upvotes: 1