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:
this.context = context;
static contextTypes: {
history: React.PropTypes.object,
location: React.PropTypes.object,
router: React.PropTypes.func.isRequired
}
ComponentName.contextTypes = {
router: React.PropTypes.func.isRequired
}
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"
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With