Get an active route with react-router in ReactJs

Karan picture Karan · Dec 7, 2017 · Viewed 7.7k times · Source

I am creating a project using reactjs.In my application i am getting the active route using this:

this.context.router.isActive

but getting undefined, i am using the react-router 4.Earlier this was worked for me when am using the lower version of react-router. Here is my code:

class NavLink extends React.Component {

    render() {


     console.log( this.context.router.isActive)
          let isActive = this.context.router.isActive(this.props.to, true);
           let className = isActive ? "active" : "";
        return(
            <li  className={className} {...this.props}>
               <Link {...this.props}/>
            </li >
        );
    }
}

NavLink.contextTypes = {
    router: PropTypes.object
};

Answer

Shubham Khatri picture Shubham Khatri · Dec 12, 2017

The architecture has changed in react-router v4 and this.context.router.isActive is no longer supported.

In react-router-v4, you could instead of creating a NavLink yourself use the exposed NavLink component.

From the documentation:

NavLink

A special version of the that will add styling attributes to the rendered element when it matches the current URL.

import { NavLink } from 'react-router-dom'

<NavLink to="/about">About</NavLink>

It also provides you an activeClassName prop:

activeClassName: string

The class to give the element when it is active. The default given class is active. This will be joined with the className prop.

<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>

Why is this.context.router.isActive not supported:

Here is an excerpt from a github issue

Rendering a <Route> does not necessarily mean "only render when you match the current location". For example, it can be used inject the router variables from the context into a component as props.

In <NavLink>, the <Route> is using the children prop, which means that it will call the children function whether or not the route matches. If the match is null, then we know that it did not match.

If you would prefer not to use <Route children> in this way, React Router offers an imperative approach with the matchPath function. This is what <Switch>es and <Route>s use internally to match a location against a path.

If your component is not receiving the Router props, then you could inject it using the withRouter HOC

import { withRouter } from 'react-router';

export class withRouter(MyComponent);