With the previous react-router I was able to do this:
import {browserHistory} from 'react-router';
from my actionCreators file and I could do something like this:
...some async action completed (for example, user logged in successfully)..
browserHistory.push('/dashboard');
But with the new react-router-dom (v4) it seems like I can no longer import browserHistory just like that and that the only way to access the history object is from a React components props
this.props.history
What would be a way to redirect my user to a new page after an async redux action has completed using react-router-dom?
We would obviously want some additional logic in there, but the point is that we can access the history object through props , even though no props were passed to Login , and use history. push to push a new entry onto the history stack.
Using history.push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.
withRouter is what you're looking for.
"You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component."
import React, { PropTypes } from 'react'
import { withRouter } from 'react-router'
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>You are now at {location.pathname}</div>
)
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With