0

I am trying not to use : if(window.location) to get access to my current route.

I am working on a code where the router is already defined, and the component is already written. I am trying to access the router information from the component because I need to apply a classname depending on the route.

Here's how the router looks like:

export const createRoutes = (dispatch, getState) => ( <Route component={AppLayout} > <Route path="/" component={Home} onEnter={(nextState, replaceState) => { console.log('on Enter / = ', nextState); nextState.test = 'aaaa'; //can't seem to pass states here.... }} />

then in my component:

render() {
    //I want to access my super router or location . in fact
    // I just want to know if currentURl === '/'

    //and after reading the react-router doc 5 times - my head hurts 
    // but I still hope to get an answer here before putting a window.location
 }
` 
Ant
  • 1,812
  • 5
  • 22
  • 39

1 Answers1

3

Depending on which version of React Router you're using you have access to different objects available on the context of a component.

MyComponent.contextTypes = {
    location: React.PropTypes.object
}

which will enable you to do the following

render() {
    if (this.context.location.pathname === '/') {
        return <h1>Index</h1>;
    } else {
        return <h2>Not index</h2>;
    }
}
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92