Programmatically navigating in React-Router v4

You are using react-router v4, so you need to use withRouter with your component to access the history object’s properties, then use history.push to change the route dynamically.

withRouter:

You can get access to the history object’s properties and the closest
‘s match via the withRouter higher-order component. withRouter
will re-render its component every time the route changes with the
same props as render props: { match, location, history }.

Like this:

import {withRouter} from 'react-router-dom';

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>
        )
    }
}

export default withRouter(WelcomeForm);

Leave a Comment