I am new to the ReactJS world, and would like to know how can I pass active class name to the <li>
element instead of <a>(Link)
element.
Now I have this kind of code. The anchor class changes when clicked.
<li><IndexLink to='/' activeclassName='active'>A</IndexLink></li>
<li><Link to='/b' activeclassName='active'>B</Link></li>
<li><Link to='/c' activeclassName='active'>C</Link></li>
But I would like to get something similar to:
<li activeclassName='active'><IndexLink to='/'>A</IndexLink></li>
<li activeclassName='active'><Link to='/b'>B</Link></li>
<li activeclassName='active'><Link to='/c'>C</Link></li>
Thanks in advance
I'm using React Router v4.2 and I couldn't get the reference to the router object from the wrapping component, because the context is not available.
This did not work:
I like @mpen's answer, but I'm using nested routes and I don't want to change the file where I have the routing component defined.
What I did is compared the location.pathname with to :
Using React Router v4, I only got it to work by including the
<li>
tags within the NavLink component. The solutions which have the<li>
tags wrapping the links resulted in the HOME<li>
tag always having theactive
class.I adjusted the
li
anda
CSS selectors accordingly.You need to enclose your
<li>
as a router aware component:Usage:
I took inspration from the react-router-bootstrap module, https://github.com/react-bootstrap/react-router-bootstrap/blob/master/src/LinkContainer.js. I didn't test it though so let me know how it goes.
In stead of using
<Link />
, I use<NavLink />
and It works as well.Usage:
The other answers don't seem to work in React Router v4. Here's how you can do it: