Here is the problem I am facing:
I am using react-router and redux-form in my application. In one of my forms, I want to use the router to go back to the main page after the submission succeeds. Here is the code I have:
function Router(target) {
target.contextTypes = target.contextTypes || {};
target.contextTypes.router = React.PropTypes.func.isRequired;
}
enter code here
@Router
@reduxForm({
form: 'editLocation',
fields: LocationFormFields,
validate: ValidateLocationForm,
onSubmitSuccess: () => {
var path = '/locations';
this.context.router.push(path);
},
onSubmitFail: () => {
console.log('failed');
}
}, MapStateToProps)
export class EditLocation extends React.Component .....
The problem is that 'this.context' is not defined inside the onSubmitSucess method.
I know that I can take care of this using browserHistory directly. However, I don't want to really go that route and I want to use this.cotext. Any ideas?
I think your best bet is to not make your form component the same as your route component, and pass in the onSubmitSuccess
as a prop to your form component.
import { withRouter } from 'react-router'
@withRouter // injects router as prop
export class EditLocation extends React.Component {
handleSubmitSuccess() {
this.props.router.push('/locations')
}
render() {
return <EditLocationForm
onSubmitSuccess={this.handleSubmitSuccess}/>
}
}
@reduxForm({
form: 'editLocation',
fields: LocationFormFields,
validate: ValidateLocationForm,
onSubmitFail: () => {
console.log('failed');
}
}, MapStateToProps)
export class EditLocationForm extends React.Component .....