I'm in the process of learning React Router, and I can't seem to figure out what is currently the recommended way to redirect. I've read many articles and StackOverflow posts, but there is so much variety that I'm unsure of which one to implement for the current version of React Router.
What I'm trying to do is to redirect after an AJAX call using axios.
axios.post('/some-route')
.then(/*I want to redirect here*/)
Note: this code lives inside a function, inside a React.Component, that is called upon the submission of a form.
How do I accomplish this?
Please kindly let me know what details you need.
You can use browserHistory
:
import { browserHistory } from "react-router";
browserHistory.push({
pathname: '/your/path'
});
This answer is for
react-router-v4
.
If you want to redirect
from the same component
(not from some action
) and this component
is rendered by some route
then you can use history
object passed in the props
.
componentDidMount(){
if(this.state.some_param){
this.props.history.push("/some_location")
}
}
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 history in your router,
import history from "./history"
<Router history = {history}>
//other code
</Router>
now you can use this history object anywhere for 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/[email protected]/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>
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