Programmatically navigating in React-Router v4

Viewed 12311

How can I move to a new page after some validation is done with React Router V4? I have something like this:

export class WelcomeForm extends Component {

    handleSubmit = (e) => {
        e.preventDefault()

        if(this.validateForm())
            // send 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>
        )
    }
}

I would like to send the user to another route. I had a look at Redirect but it seems like it would delete the current page from the history which I don't want.

4 Answers

If you are using TypeScript extends your component using React.Component<RouteComponentProps> to get this.props.history.push properly

class YourComponent extends React.Component<RouteComponentProps> {
    constructor(props: Readonly<RouteComponentProps>) {
        super(props)
    }

    public render(){
        // you can access history programmatically anywhere on this class
        // this.props.history.push("/")
        return (<div/>)
    }
}
return default withRouter(YourComponent)
Related