React Router v4 - Redirect component (updated 2017/04/15)
The recommended v4 method is to allow your rendering method to intercept the redirect. Use the state or props to determine whether the redirection component (which then calls the redirection) should be displayed.
import { Redirect } from 'react-router'; // ... your class implementation handleOnClick = () => { // some action... // then redirect this.setState({redirect: true}); } render() { if (this.state.redirect) { return <Redirect push to="/sample" />; } return <button onClick={this.handleOnClick} type="button">Button</button>; }
Link: https://reacttraining.com/react-router/web/api/Redirect
React Router v4 - Help Router Context
You can also use the Router context that appears in the React component.
static contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired, staticContext: PropTypes.object }).isRequired }; handleOnClick = () => { this.context.router.push('/sample'); }
This is how <Redirect /> works under the hood.
Link: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60
React Router v4 - Object of history with an external mutation
If you still need to do something similar to the v2 implementation, you can create a copy of BrowserRouter and then set history as an exported constant. Below is a basic example, but you can build it, if necessary, using custom details. There are marked reservations with life cycles, but it should always repeat the Router, as in v2. This can be useful for redirecting after an API request from an action function.
// browser router file... import createHistory from 'history/createBrowserHistory'; import { Router } from 'react-router'; export const history = createHistory(); export default class BrowserRouter extends Component { render() { return <Router history={history} children={this.props.children} /> } } // your main file... import BrowserRouter from './relative/path/to/BrowserRouter'; import { render } from 'react-dom'; render( <BrowserRouter> <App/> </BrowserRouter> ); // some file... where you don't have React instance references import { history } from './relative/path/to/BrowserRouter'; history.push('/sample');
Latest BrowserRouter for extension: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js
React Router v2
Click the new state into the browserHistory instance:
import {browserHistory} from 'react-router'; // ... browserHistory.push('/sample');
Link: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md