Categories
React Answers

How to go back to the previous route with React Route v4?

Spread the love

To go back to the previous route with React Route v4, we can use the history.goBack method.

For instance, we write

//...
import { withRouter } from "react-router-dom";

class Demo extends Component {
  //...
  constructor(props) {
    super(props);
    this.goBack = this.goBack.bind(this);
  }

  goBack() {
    this.props.history.goBack();
  }
  //...
}

export default withRouter(Demo);

to call the this.props.history.goBack method in goBack.

We get the method because we call withRouter with Demo to inject the history prop into the Demo component.

We call this.props.history.goBack method to go back to the previous route.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *