Hugo Martinez
Hugo Martinez

Reputation: 78

Can't access context.router with react-router-redux

I m currently using react-router-redux on a project and everything is working fine except for the fact that i can't figure out how to access the react-router router.

@connect((state, props) => {
    return  {
                notification:state.getIn(['_display', 'notification']),
                loadingScreen:state.getIn(['_display', 'loadingScreen']),
                route:props.location.pathname
            };
})
export default class Consultation extends React.Component {

    constructor(props,context) {
        super(props, context);
        console.log(context.router);
    }

    componentDidMount(){
        const { router } = this.context;
        .....
    }

    render(){
     ....
    }
}
Consultation.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store:React.PropTypes.object
};

this.context.router is always undefined and i ve tried a lot of things unsuccessfully

i m using react 0.14.6, redux 3.0.2, react-router 2.0.0, react-router-redux 4.0.0

Upvotes: 0

Views: 2625

Answers (1)

Dan Abramov
Dan Abramov

Reputation: 268255

You are putting .contextTypes on the component returned by connect() instead of your own component. This is why context isn’t made available to your component.

Try this instead:

class Consultation extends React.Component {
    constructor(props, context) {
        super(props, context);
        console.log(context.router);
    }

    componentDidMount(){
        const { router } = this.context;
        .....
    }

    render(){
     ....
    }
}
Consultation.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store:React.PropTypes.object
}

export default connect(...)(Consultation)

Note that we first specify contextTypes, and export the connected component, rather than assign contextTypes to an already connected component which you get from the @connect decorator. By the way this is yet another reason to avoid decorators!

Upvotes: 2

Related Questions