Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing issue: this.context.router not defined when trying to re-route

I'm trying to automatically change the path after n seconds. (without using <Link to="/home">Home</Link> ).

My code looks like this:

class ComponentName extends Component {
  constructor (props, context) {
    super(props, context);
  }
  componentDidMount () {
    setTimeout(function(){
      this.context.router.transitionTo('/home');
    }.bind(this), 3000)
  }
  render() {return (<div>..will go to the home page</div>)}
}

ComponentName.contextTypes = {
  router: function () { 
    return React.PropTypes.func.isRequired;
  }
};
export default ComponentName;

This is the error I'm getting

Uncaught TypeError: Cannot read property 'transitionTo' of undefined on line this.context.router.transitionTo('/home'); aka this.context.router is undefined.

this.context is defined, so no problem there afaik.

Things I've tried some of the following:

  • In the constructor:
  • this.context = context;
    

  • In the class:
  • static contextTypes: {
      history: React.PropTypes.object,
      location: React.PropTypes.object,
      router: React.PropTypes.func.isRequired
    }
    

  • Before exporting (tried with & without function):
  • ComponentName.contextTypes = {
      router: React.PropTypes.func.isRequired
    }
    

  • I've also tried changing route to history, or just calling the function on the context:
  • this.context.history.transitionTo('/home');
    this.context.transitionTo('/home');
    this.transitionTo('/home');
    

    Fact is that this.context.router is still undefined, I've searched more threads (mainly this one: https://github.com/rackt/react-router/issues/975 ) on this and still couldn't find something that would work for me.

    Note: I'm using ES6 &

    "react": "^0.14.0",
    "react-router": "^1.0.0-rc3"
    
    like image 980
    Sanda Avatar asked Nov 21 '22 02:11

    Sanda


    1 Answers

    There's already an answer explaining how to programmatically force a new route for every react-router version: https://stackoverflow.com/a/31079244/5810646

    You are (or should I use "were") trying to force a new route after 3 seconds on your page. It shouldn't be a history related problem, as the version of react-router you're using is 1.0.0-rc3 (which doesn't seem by the way looking at your code).

    You can leverage history to push a new route if you're using react-router 2.x.x:

    import { browserHistory } from 'react-router'
    

    And then doing:

    browserHistory.push('/some/path')
    
    like image 168
    iba Avatar answered Dec 04 '22 12:12

    iba