This answer is for react-router-v4 .
If you want redirect from the same component (not from some action ), and this component displayed by some route , then you can use the history object passed to props .
componentDidMount(){ if(this.state.some_param){ this.props.history.push("/some_location") } }
The best way is to create your own history object. You can use this history object in any action .
//history.js import createHistory from 'history/createBrowserHistory' export default createHistory()
then you can use this story in your router,
import history from "./history" <Router history = {history}> //other code </Router>
Now you can use this story object anywhere to redirect,
axios.post('/some-route') .then(res=>{ history.push("/some_location") })
const {Component} = React const {render} = ReactDOM const {Router, Link, Route, Switch, withRouter, Redirect} = ReactRouterDOM const createHistory = History.createHashHistory const myhistory = createHistory() class App extends Component{ redirectToHome(){ myhistory.push("/home") } redirectToAbout(){ myhistory.push("/about") } render(){ return( <div> <Route path = "/home" component = {Home} /> <Route path = "/about" component = {About} /> <button onClick = {this.redirectToHome}>Redirect to home</button> <button onClick = {this.redirectToAbout}>Redirect to about</button> </div> ) } } const Home = ()=>{ return( <div> Home </div> ) } const About = ()=>{ return( <div>About</div> ) } render(<Router history = {myhistory}><App/></Router>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <script src="https://unpkg.com/ react-router-dom@4.1.1 /umd/react-router-dom.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/history/4.6.3/history.min.js"></script> <div id="app"></div>
source share