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?
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:
- Creating a new
browserHistory
won't work because<BrowserRouter>
creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the<BrowserRouter>
.browserHistory
is not exposed by react-router in v4, only in v2.
Instead you have a few options to do this:
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:
import React from "react";
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path");
}
...
}
export default withRouter(MyComponent);
Check out the official documentation for more info:
You can get access to the
history
object’s properties and the closest<Route>
'smatch
via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as<Route>
render props:{ match, location, history }
.
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:
import React from "react";
import PropTypes from "prop-types";
class MyComponent extends React.Component {
static contextTypes = {
router: PropTypes.object
}
constructor(props, context) {
super(props, context);
}
...
myFunction() {
this.context.router.history.push("/some/Path");
}
...
}
Have a look at the official documentation on context:
If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.
If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.