Reputation: 3636
I want to know how could I control the className of a Navlink so if the actual path is X, then the class of a NavLink is active. I did it before using Laravel and simple bootstrap but I dont know how to do this with React and Reactstrap.
Example Laravel:
<a href="{!!URL::to('link1')!!}" class="{{Request::is('link1') ? 'activeMenu' : '' }} >Link1</a>
My ReactJS code:
<Nav className="navbar-logged">
<NavItem>
<NavLink className="nav-link-gdc" href="/">HOME</NavLink>
<NavLink className="nav-link-gdc" href="#">LINK1</NavLink>
<NavLink className="nav-link-gdc" href="#">LINK2</NavLink>
<NavLink className="nav-link-gdc" href="#">LINK3</NavLink>
<NavLink className="nav-link-gdc" href="#">LINK4</NavLink>
</NavItem>
</Nav>
Upvotes: 0
Views: 2841
Reputation: 9848
Yes, we can control the class name of the NavLink:-
const pathName = this.props.history.location.pathname;
<NavLink to='/pathNameHome' className='header__route--link'
activeClassName={pathName === '/home || pathName === '/dashborad' ? 'header__route--active' : ''} >
In above code 'pathName' we are taking from the history location, if you want to put condition on pathName then you can also do that {pathName === '/home || pathName === '/dashborad' ? 'header__route--active' : ''} in this block we are comparing the path , if you want directly then you can write activeClassName= 'header__route--active' so once the path is selected the class name 'header__route--active will activate else the class name header__route--link will be activated by default.
Upvotes: 0
Reputation: 1713
Just add your path in to
argument, rather than in href
. Like this:
`<NavLink className="nav-link-gdc" to="/">HOME</NavLink>`
And it will add class active
automatically. See the docs for NavLink
Then you will have to add some router logic to be able to mark nav link as active or, if you don't need changing urls in address bar, make something like this answer on SO
Upvotes: 3