Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router <NavLink> with active style doesn't work as I required with root URL

I used this NavLinks in the main menu. The issue is that when '/Test/car' link is clicked '/Test' link is also applying the styles. I believe it's because '/Test' suppose to be the root of other links. so it make sense.

But I want '/Test' link also to work like other links when applying the active style. So '/Test' will get applied the styles only when that 'Home' link is clicked. How I get that done (in a reactjs way)?

<Route exact path="/TEST" component={Home}></Route>
<Route path="/TEST/car" component={Car}></Route>
<Route path="/TEST/van" component={Van}></Route>
<Route path="/TEST/train" component={Train}></Route>

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/car" onClick={this.closeMenuForMobile.bind(this)} >Car</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/van"  onClick={this.closeMenuForMobile.bind(this)} >Van</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/train" onClick={this.closeMenuForMobile.bind(this)}>Train</NavLink>
like image 638
Lakshitha Ruwan Avatar asked Jul 18 '17 05:07

Lakshitha Ruwan


People also ask

How do I style a NavLink in react?

In our routing app, we have three routes which are [home, /users, /contact] Let's style them using NavLink. We need to add a new prop called activeClassName to the NavLink component so that it applies that class whenever the route it is active. Now you can see a red color is applied to the active routes.

Can I use onClick on NavLink?

onClick on a NavLink component should work. Did you take the onClick prop in the Tile component and add it to the NavLink ? the way you are defining onClick is partially correct, onClick will become the part of props object. You need to use it on NavLink in Tile component.

Which is a difference between Link /> and NavLink />?

Conclusion. The NavLink is used when you want to highlight a link as active. So, on every routing to a page, the link is highlighted according to the activeClassName . Link is for links that need no highlighting.


1 Answers

Just like your path use exact

Change this

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>

To this

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} exact to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>

Source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md#exact-bool

like image 117
Hana Alaydrus Avatar answered Oct 17 '22 02:10

Hana Alaydrus