In the current version of React Router (v3) I can accept a server response and use browserHistory.push
to go to the appropriate response page. However, this isn't available in v4, and I'm not sure what the appropriate way to handle this is.
In this example, using Redux, components/app-product-form.js calls this.props.addProduct(props)
when a user submits the form. When the server returns a success, the user is taken to the Cart page.
// actions/index.js
export function addProduct(props) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/cart'); // no longer in React Router V4
});
}
How can I make a redirect to the Cart page from function for React Router v4?
Here's my hack (this is my root-level file, with a little redux mixed in there - though I'm not using
react-router-redux
):I can then use
window.appHistory.push()
anywhere I want (for example, in my redux store functions/thunks/sagas, etc) I had hoped I could just usewindow.customHistory.push()
but for some reasonreact-router
never seemed to update even though the url changed. But this way I have the EXACT instancereact-router
uses. I don't love putting stuff in the global scope, and this is one of the few things I'd do that with. But it's better than any other alternative I've seen IMO.you can use it like this as i do it for login and manny different things
this.context.history.push
will not work.I managed to get push working like this:
Simplest way in React Router 4 is to use
But to use this method, your existing component should have access to
history
object. We can get access byIf your component is linked to
Route
directly, then your component already has access tohistory
object.eg:
Here
ViewProfile
has access tohistory
.If not connected to
Route
directly.eg:
Then we have to use
withRouter
, a heigher order fuction to warp the existing component.Inside
ViewUsers
componentimport { withRouter } from 'react-router-dom';
export default withRouter(ViewUsers);
That's it now, your
ViewUsers
component has access tohistory
object.React Router v4 is fundamentally different from v3 (and earlier) and you cannot do
browserHistory.push()
like you used to.This discussion seems related if you want more info:
Instead you have a few options to do this:
Use the
withRouter
high-order componentInstead you should use the
withRouter
high order component, and wrap that to the component that will push to history. For example:Check out the official documentation for more info:
Use the
context
APIUsing the context might be one of the easiest solutions, but being an experimental API it is unstable and unsupported. Use it only when everything else fails. Here's an example:
Have a look at the official documentation on context: