v4 is an absolute joy to use so far! One missing piece, though, is the lack of transitionTo or any replacement for it. Is this in the cards for v4?
You can access the router through the context. This has transitionTo and replaceWith methods for navigating.
class MyComponent extends React.Component {
navigate() {
const { router } = this.context
router.transitionTo('/some/new/location')
}
}
MyComponent.contextTypes = {
router: React.PropTypes.object
}
Hi,
Sorry to ping a closed issue, but I thought accessing this.context in React was a bad idea, no? Or has that changed. It seems like having programmatic ways to navigate in an app is crucial, so if transitionTo is only going to be available through a non-recommended channel, that seems risky in the long-run.
It is possible to obscure usage of the context through higher order components (see react-redux's connect), but there isn't a good way to avoid them altogether without having every component pass the desired value as a prop.
There is currently a PR (#4044) to add a withRouter HOC that would inject the router as a prop to the component that it wraps. Until that is merged, any examples will have to use the context.
Cool, thanks.
What if I'm not on a react component? I use an API client that upon receiving a 401 will need to redirect people to the login route, but it's not a react component, only a service that gets imported to be used, what do you think would be the best way to achieve this?
@gaboAcosta Just do what Browser/Hash/MemoryRouter does and create your own history and pass that into Router whenever you get to the React parts of your app: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js#L19
Most helpful comment
Hi,
Sorry to ping a closed issue, but I thought accessing
this.contextin React was a bad idea, no? Or has that changed. It seems like having programmatic ways to navigate in an app is crucial, so iftransitionTois only going to be available through a non-recommended channel, that seems risky in the long-run.