Answer a question

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

Answers

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 = '';
  }
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐