Reputation: 320
react v0.14.7 / react-router: v2.0.1
I have my Routes set up as follows:
import { Router, Route, IndexRoute, hashHistory } from "react-router"
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/locations" component={Locations}/>
<Route path="/products" component={Products}/>
</Route>
</Router>,
document.getElementById('app'));
I'm trying to write a method in one of my React classes (created using the following API)
export default class MyClass extends React.Component {...}
...that determines if the current URL's path is a particular route's path.
For example. Assuming the current URL is http://domain/products
then calling:
isActive('/products')
would return TRUE
I'm aware of React Router's Link
object activeClassName
. But I need to write something that looks this up programmatically in a different location to where I defined the <link/>
objects.
Looking in node_modules/react-router/
I can see modules/isActive.js
that does what I need, however it's not export
ed in modules/index.js
, so i'm assuming I cannot access it?
I also see from the API docs that there is an RouterContext isActive method, but again, I don't know how to call this?
Upvotes: 1
Views: 4933
Reputation: 320
OK thanks to Mike 'Pomax' Kamermans, I resolved the issue like so:
Changed create class API from:
export default class MyClass extends React.Component {
...
}
to:
export default React.createClass({
...
})
And added the following contextTypes
definition to the class:
export default React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render(){
console.log(this.context.router.isActive('/foo')); // Now works :)
...
}
})
Upvotes: 1