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?
Use Callback. It worked for me!
In component, you just have to add the callback
If you are using Redux, then I would recommend using npm package react-router-redux. It allows you to dispatch Redux store navigation actions.
You have to create store as described in their Readme file.
The easiest use case:
Second use case with Container/Component:
Container:
Component:
In this case you're passing props to your thunk. So you can simply call
If this isn't the case you can still pass history from your component
You can use the
history
methods outside of your components. Try by the following way.First, create a
history
object used the history package:Then wrap it in
<Router>
(please note, you should useimport { Router }
instead ofimport { BrowserRouter as Router }
):Change your current location from any place, for example:
UPD: You can also see a slightly different example in React Router FAQ.
This is how I did it:
Use
this.props.history.push('/cart');
to redirect to cart page it will be saved in history object.Enjoy, Michael.