Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  190] [ 4]  / answers: 1 / hits: 39575  / 8 Years ago, mon, october 24, 2016, 12:00:00

I have a navigation component which renders each navigation link.
The return of this component looks like this:



     return (
<li key={`nav-list-${el.title}-${index}`}>
<Link to={{pathname: '/c/' + el.urlkey}}
activeClassName={s.active}>{el.title}</Link>
{subNav}
</li>
);


The active class is only set on a page refresh. When clicking through the links the active indicator stays at the initial link.



I'm not using Redux so it doesn't seem to be related to this issue: activeClassName does not work on the sideMenu when clicking on the link



My route look like this:



      <Route path=/c/:category(/:title) component={CategoryView} name=category />


using React-Router 2.8.1 and browserHistory


More From » reactjs

 Answers
10

I didn't want to upgrade just yet as it was causing more issues than it resolved. And I wasn't using Redux so the whole connect thing didn't apply. I tried render both pure and unpure (using the pure-render decorator) with no result.



So I decided to write the link handling manually. It's super verbose I know but it works!



I added the router context:



static contextTypes = {
router: React.PropTypes.object
};


The render returns:



return (
<li key={`nav-${el.title}`} className={`${isActiveClass}`}>
<a onClick={this.state.LinkClick} data-item={urlkey}>{el.title}</a>
</li>
);


The click handler looks like this:



LinkClick(e){
e.preventDefault();
const elem = e.currentTarget;
const item = elem.dataset.item;
this.context.router.push('/c/'+item);
this.setState({
activeLink: item
});
}


Finally I set the class in the render:



  const activeLink = this.state.activeLink;
let isActiveClass = '';
let navLinks = map(availableCategories, (el, index) => {
const urlkey = el.urlkey;

// Check the active item on page render
const isActive = this.context.router.isActive('/c/' + urlkey);

if(activeLink === urlkey || isActive){
isActiveClass = s.active;
} else {
isActiveClass = '';
}

[#60299] Friday, October 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
2 Years ago
;