3

I am trying to programmatically navigate using react-router and I can't seem to be able to do so.

I have read other related questions, such as this one that seems to work for everyone else, but to no avail.

I am using react-router version 2.4.1, and to my understanding it should be accomplished by:

this.context.router.push('/');

or even:

browserHistory = require('react-router').browserHistory;
//...
var browserHistory.push('/');

But with either approaces all I seem to accomplish is a URL rewrite, with no actual routing going on.

I do have a route registered for '/' on my router.

What am I missing? I am inches away from a window.location = '/' on what is otherwise a Single Page Application :(

Community
  • 1
  • 1
rgcalsaverini
  • 626
  • 6
  • 16

3 Answers3

3

I know this is a few months old but just in case anyone is encountering a similar problem.

A simple fix could be to add this code:

static contextTypes = {
  router: PropTypes.object,
};

and then you can use: this.context.router.push('/foo');

Reference

Johhan Santana
  • 2,336
  • 5
  • 33
  • 61
  • add this where in your code? Suppose you're using a `class myComponent extends Component{...}` – Philll_t Feb 25 '17 at 03:28
  • Okay, so within the Class. In this case, if you're running ES6 you will get an error. Not sure how to fix this. – Philll_t Feb 27 '17 at 16:30
1

So, apparently a third-party component fiddling with the context and children was to blame. Removed it and now it works as expected.

If anyone is facing this, try to look at how the components on your route are handling context and children.

rgcalsaverini
  • 626
  • 6
  • 16
  • This is not working for me, I tried `this.context.router.push('/');`, using router v2.4.1 too. I don't have any 3rd party React components that would mess with `this.context`, at least not that I'm aware of. Using `ReactJS v15.1.0`. Tried some suggestions from here: http://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router, tired here: https://github.com/reactjs/react-router/blob/master/docs/API.md#withroutercomponent Still no luck. – Giant Elk Jun 18 '16 at 23:07
  • I got it working, from following this: https://github.com/reactjs/react-router-tutorial/tree/master/lessons/12-navigating And for ES6 React check here for example of contextTypes: blog.ricardofilipe.com/post/react-and-es6, hint: YourComponentName.contextTypes = { router: React.PropTypes.object }; – Giant Elk Jun 18 '16 at 23:25
1

Following code is a working sample for navigation

Code to Navigate,

handleClick(e) {
    e.preventDefault();
    this.context.router.push('/aboutus');
  }

And for the React Component don't forget to refer Context

Item.contextTypes = {
  router: PropTypes.object.isRequired
};
Nazeel
  • 326
  • 3
  • 10