How to navigate programmatically in React Router v4?

Sometimes, we want to navigate programmatically in React Router v4.

In this article, we’ll look at how to navigate programmatically in React Router v4.

How to navigate programmatically in React Router v4?

To navigate programmatically in React Router v4, we can use the this.props.history.push method.

For instance, we write

import React from "react";
import { withRouter } from "react-router-dom";

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: "",
    };
  }

  submit = (event) => {
    event.preventDefault();
    this.props.history.push('/theUrlYouWantToGoTo');
  };

  render() {
    return (
      <form onSubmit={this.submit}>
        <input
          type="text"
          onChange={(event) => this.setState({ input: event.target.value })}
        />

        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default withRouter(Form);

to call this.props.history.push with '/theUrlYouWantToGoTo' to go to /theUrlYouWantToGoTo when the submit method is called.

We call withRouter with Form so that history is injected into the props of Form.

Conclusion

To navigate programmatically in React Router v4, we can use the this.props.history.push method.