'Get an active route with react-router in ReactJs
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
};
Solution 1:[1]
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.
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);
Solution 2:[2]
A simple way to style active router
import NavLink
import { NavLink } from 'react-router-dom';
<NavLink className={({ isActive }) => (isActive ? 'active-link' : 'link')} to="/home">Home</NavLink>
in style.css
.active-link {
color: hsl(96, 82%, 35%);
}
customize the style looks more beautiful.
~cheers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Al Mamun Khan |