I try to do a simple redirect in a function...
I tried this:
Router.browserHistory.push('/dashboard'); But then I got this error:
Uncaught TypeError: Cannot read property 'push' of undefined whats my fail?
I try to do a simple redirect in a function...
I tried this:
Router.browserHistory.push('/dashboard'); But then I got this error:
Uncaught TypeError: Cannot read property 'push' of undefined whats my fail?
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 available form react-router-dom package from v4 , and is separated to history package.
Navigating with WithRouter
You can rather make use of withRouter Higher Order Component and navigate with history prop
From the official documentation
You can get access to the history object’s properties and the closest <Route>'s match 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 }.
Sample snippet
import {withRouter} from "react-router"; class MyComponent extends React.Component { ... changeRoute = () => { this.props.history.push('/dashboard) } ... } export default withRouter(MyComponent); Also see this answer for more info on nesting and dynamically routing in react-router-v4
As mentioned in the comments you should use this new approach for v4 react router but if you are looking for a quick workaround you can use context. ```javascript
import { PropTypes } from 'prop-types' import React from 'react' export default class MyComponent extends React.Component { ... // redirect to dashboard redirectToDashboard = () => { this.context.router.history.push('/dashboard'); } } MyComponent.contextTypes = { router: PropTypes.object } This should do the trick