I am using ReactJS
and have a form (component) that needs to redirect to another component, if the post request is successful. I have just started using react router, so this is the way I am trying to redirect.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect, Link } from 'react-router-dom';
import NextComponent from '/NextComponent';
import axios from 'axios';
class CurrentComponent extends Component {
constructor() {
super();
this.state = {
value: ''
redirect: false
};
}
handleSubmit() {
axios.post('xxx/yyy', {
xxx: yyy
})
.then(function() {
console.log('Success');
this.setState({redirect: true});
})
.catch(function() {
console.log('Error');
});
}
render() {
return(
<div>
<form>
<div className="form-group">
<input type="name" placeholder="name" />
</div>
<div className="form-group">
<button type="button" onClick={this.handleSubmit.bind(this)} >Submit</button>
{this.state.redirect &&
<Redirect to={{
pathname: '/nextcomponent',
state: {from: this.state.value}
}} />
}
</div>
<Router>
<Route path="/nextcomponent" component={NextComponent} />
</Router>
</form>
</div>
);
}
}
export default PresentComponent;
It is not redirecting and I have been trying to figure this out. I am sure there are better solutions available, but due to my lack of knowledge I am unsure of implementing it. Any help is appreciated. Thank you.
This worked for my use case not sure about you. Try this -
Modify your logic or encapsulate it into
<Route />
like in this example.Redirect
is an export ofreact-router
notreact-router-dom
. Therefore, you need to import it like:Redirect doc
If you're using react-router 4, history is available through context:
So you'd modify your handleSubmit:
See this answer for other ways of altering history without conditional routing.
If you are using React-router-dom, then please check below given link.
https://reacttraining.com/react-router/web/example/auth-workflow
Using react-router 2.8
I used the hashHistory from react-router to achieve this
then where I want to redirect:
Probably you are not getting the
state
after post call, try modifying thehandleSubmit
method as:Update as per new code: