[React Router v4] Style a Link that is Active with NavLink

We often need to be able to apply style to navigation links based on the current route. In React Router v4 you can easily accomplish this with the NavLink component. In this lesson, we will step through three ways to accomplish styling links through the use of an active class with the NavLink component.

 

There are three ways to check an link is active or not and add active class for it:

const isLinkActive = (match, location) => {
    return match
};

const Nav = () => (
  <nav>
      <NavLink to="/" exact activeStyle={{color: 'pink'}}>Home</NavLink>
      <NavLink to="/about" activeClassName="active">About</NavLink>
      <NavLink replace
               to={{pathname: '/contact'}}
               isActive={isLinkActive}
               activeClassName="active"
      >Contact</NavLink>
  </nav>
);

 

'isActive' prop allows you to decide whether or not to apply active class.

posted @ 2017-03-21 04:10  Zhentiw  阅读(455)  评论(0编辑  收藏  举报