Depending on how you want your redirect to behave there are several options: React router docs
Redirect component
Rendering a will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
to: string
- The URL to redirect to.
to: object
- A location to redirect to.
push: bool
- When true, redirecting will push a new entry onto the history instead of replacing the current one.
Example: <Redirect push to="/somewhere"/>
import { Route, Redirect } from 'react-router'
export class WelcomeForm extends Component {
handleSubmit = (e) => {
e.preventDefault()
if(this.validateForm())
<Redirect push to="/life"/>
}
render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}
Using withRouter
HoC
This higher order component will inject the same props as Route. However, it carries along the limitation that you can have only 1 HoC per file.
import { withRouter } from 'react-router-dom'
export class WelcomeForm extends Component {
handleSubmit = (e) => {
e.preventDefault()
if(this.validateForm())
this.props.history.push("/life");
}
render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}