Programmatically navigating using React Router

The primary way to do that is by using the <Redirect/>component. The typical way is routing on some kind of user event. Refer the below example.

class Register extends React.Component {

  state = {

    toDashboard: false,

  }

  handleSubmit = (user) => {

    saveUser(user)

      .then(() => this.setState(() => ({

        toDashboard: true

      })))

  }

  render() {

    if (this.state.toDashboard === true) {

      return <Redirect to='/dashboard' />

    }

    return (

      <div>

        <h1>Register</h1>

        <Form onSubmit={this.handleSubmit} />

      </div>

    )

  }

}

Another way to do it is by pushing a new history to props.history.

//using ES6

import React from 'react';

class App extends React.Component {

  constructor(props) {

    super(props)

    this.handleClick = this.handleClick.bind(this)

  }

  handleClick(e) {

    e.preventDefault()

    this.props.history.push('/redirected');

  }

  render() {

    return (

      <div>

        <button onClick={this.handleClick}>

          Redirect!!!

        </button>

      </div>

    )

  }

} 

export default App;

You can use withRouter method also. Please check out the below example.

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

class YourClass extends React.Component {

  yourFunction = () => {

    doSomeAsyncAction(() =>

      this.props.history.push('/other_location')

    )

  }

 

  render() {

    return (

      <div>

        <Form onSubmit={ this.yourFunction } />

      </div>

    )

  }

} 

export default withRouter(YourClass);