react-router icon indicating copy to clipboard operation
react-router copied to clipboard

this.context.router is undefined

Open tjwebb opened this issue 11 years ago • 94 comments

I just upgraded to react-router (and react) 0.13, and got rid of all the deprecated State mixins. Using this.context.router doesn't seem to work. I just see this everywhere:

Uncaught TypeError: Cannot read property 'getParams' of undefined

Is there anything additional I need to do?


Edit by Ryan Florence to get people to the answer right here at the top of the issue :dancer:

Check out the upgrade guide: https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md#012x---013x

Sorry it wasn't done w/ the release, it's been an abnormally busy month for us since we quit our jobs and started a new business :P

tjwebb avatar Mar 21 '15 06:03 tjwebb

Your class also needs

  contextTypes: {
    router: React.PropTypes.func.isRequired
  },

agundermann avatar Mar 21 '15 06:03 agundermann

I added that to my class and it seems to have no effect. I get the exact same error.

tjwebb avatar Mar 21 '15 07:03 tjwebb

I get the same thing with react 0.13.1 and react-router 0.13.1. this.context is an empty object, so this.context.router is undefined. A working react-router fiddle would be nice ;) (Removed proptype comment, didn't notice it was contextTypes, sorry)

robbestad avatar Mar 21 '15 07:03 robbestad

In general, I don't like this switch to relying on context everywhere. I'd rather have a clear, well-defined API that I can use rather than rely on invisible magic that's impossible to debug when it breaks. There's no stacktrace, no actual error anywhere, and no trail leading to anywhere inside of react-router. It's just... broken.

tjwebb avatar Mar 21 '15 07:03 tjwebb

Adding PropTypes shouldn't matter because that's just validation.

That's true for props, but not for context. I guess the reasoning behind this is to make people use context in a declarative fashion and not overuse it. Without it, a component making heavy use of context would be very hard to understand and reuse. Unlike with props, you have no idea where the data is coming from.

In general, I don't like this switch to relying on context everywhere. I'd rather have a clear, well-defined API that I can use rather than rely on invisible magic that's impossible to debug when it breaks

I never really liked the usage of context either to be honest. But without it, there's no way the router can provide things like a <Link> that can be used anywhere in your render tree; you would need to pass everything via props.

That's also the reason why the mixins and components have been relying on context under the hood for quite some time. In that sense, I think that the new API is less magical, since it doesn't attempt to hide the usage of context.

Comparing the two

React.createClass({
  mixins: [State],
  someFn: function(){
    this.getParams();
  }
});

React.createClass({
  contextTypes: {
    router: React.PropTypes.func
  },
  someFn: function(){
    this.context.router.getCurrentParams();
  }
});

In my opinion, the context way seems less magical, more declarative and doesn't rely on mixins (which was the main motivation behind this change iirc).

A working react-router fiddle would be nice

I updated the examples.

agundermann avatar Mar 21 '15 08:03 agundermann

I see the reasoning behind the change, so I support it, even though it makes the code a little bit uglier. ;)

Adding contextTypes and replacing this.getParams() with this.context.router.getCurrentParams() was all it took to make things work for me, so I'm happy.

robbestad avatar Mar 21 '15 08:03 robbestad

I updated the examples.

Where are these fiddles?

tjwebb avatar Mar 21 '15 16:03 tjwebb

In the repo: https://github.com/rackt/react-router/tree/master/examples Commit: 1b2293b0be7f4c2eeaff0afe9d8c84430ef22e17

To run locally, clone the repo, install npm dependencies and do "npm run examples".

agundermann avatar Mar 21 '15 16:03 agundermann

Here's an example High-order Component whose sole purpose is to retrieve the router from the context and expose it in this.props. A bit more future-proof than using mixins or context directly.

function ExposeRouter(ComponentClass) {
  return React.createClass({
    displayName: 'ExposeRouter',

    contextTypes: {
      router: React.PropTypes.func.isRequired,
    },

    render() {
      return <ComponentClass {...this.props} router={this.context.router}/>;
    }
  });
}

alexkirsz avatar Mar 21 '15 16:03 alexkirsz

Keep using the mixins for now, we're not super excited about this.context.router either. What do you think about injecting this.props.router to your handlers automatically?

ryanflorence avatar Mar 21 '15 17:03 ryanflorence

Keep using the mixins for now, we're not super excited about this.context.router either.

I suggest removing the deprecation warning then, otherwise it might be confusing for users (like me :wink:).

What do you think about injecting this.props.router to your handlers automatically?

Sounds good to me, although a bit cluttered, right now props really are the only way to safely pass stuff down the tree.

pscanf avatar Mar 21 '15 20:03 pscanf

Using version 0.13.1 of react and react-router the following seems to work for me:

import React from 'react';
class LoginPage extends React.Component {
  ...
  onChange() {
    this.context.router.replaceWith('/');
  }
  ...
}

LoginPage.contextTypes = {
  router: React.PropTypes.func.isRequired
};

export default LoginPage;

MariusRumpf avatar Mar 21 '15 22:03 MariusRumpf

MariusRumpf +100500

olegsmetanin avatar Mar 21 '15 22:03 olegsmetanin

My context object is also empty on 0.13.1.

akinnee avatar Mar 22 '15 00:03 akinnee

@MariusRumpf You're a true hero. Thanks man!

tylermcginnis avatar Mar 22 '15 01:03 tylermcginnis

Hm, perhaps I'm missing something in @MariusRumpf's implementation. Perhaps someone could create an example with this method?

sgehly avatar Mar 22 '15 03:03 sgehly

I'm not sure what's going on here; everyone's just posting examples of code I already have, except mine isn't working.

I did what the warnings said and stopped using mixins. Now I'm being told to start using mixins again. Can we please decide on what the API is, and stick with it?

tjwebb avatar Mar 22 '15 03:03 tjwebb

https://github.com/olegsmetanin/olegsmetanin.github.io/blob/dev/test/tests/Router.es7.jsx "react": "~0.13.1", "react-router": "~0.13.1"

import React from 'react';
import Router from 'react-router';
import { Route, RouteHandler, DefaultRoute, State, Link, Redirect } from 'react-router';
import should from 'should';

describe('Router', function () {

  it('router context is available in componentWillMount', (done) => {

    class Widget extends React.Component {
      constructor (props) {
        super(props);
        should.not.exist(this.context);
      }

      componentWillMount() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
      }

      render() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
        return <div></div>;
      }
    }

    Widget.contextTypes = {
      router: React.PropTypes.func.isRequired,
    };

    class Page extends React.Component {
      constructor (props) {
        super(props);
        should.not.exist(this.context);
      }

      componentWillMount() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
      }

      render() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
        return <div><Widget/></div>;
      }
    }

    Page.contextTypes = {
      router: React.PropTypes.func.isRequired,
    };

    class Layout extends React.Component {
      constructor (props) {
        super(props);
        should.not.exist(this.context);
      }

      componentWillMount() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
      }

      render() {
        this.context.should.have.property('router');
        this.context.router.getCurrentPath().should.equal('/page/1');
        this.context.router.getCurrentParams().should.have.property('id', '1');
        return <div><RouteHandler/></div>;
      }
    }

    Layout.contextTypes = {
      router: React.PropTypes.func.isRequired,
    };

    let routes = <Route handler={Layout}>
      <Route path="/page/?:id?" handler={Page}/>
    </Route>;

    Router.run(routes, '/page/1', function (Handler) {
      React.renderToString(<Handler />);
      done();
    });

  });

});

olegsmetanin avatar Mar 22 '15 08:03 olegsmetanin

@tjwebb My example above is using ES6, in which you cannot use mixins. You have to add the part

Page.contextTypes = {
  router: React.PropTypes.func.isRequired
};

after every class declaration in which you want to use this.context.router.

MariusRumpf avatar Mar 22 '15 12:03 MariusRumpf

Yeah this.context is undefined for me too. I'm using react router from the CDN (not sure if this makes a difference) - I've tried all the suggested solutions here and none work. The State Mixin is working though.

n1ghtmare avatar Mar 23 '15 04:03 n1ghtmare