Categories
React Answers

How to Go Back to the Previous Page with React Router v5?

Spread the love

To go back to the previous page with React Router v5, we can use the useHistory hook.

For instance, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useHistory
} from "react-router-dom";

const Foo = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>foo</p>
    </div>
  );
};

const Bar = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>bar</p>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

We have the Foo and Bar components which calls the useHistory hook.

In both components, we set the history.goBack method as the value of the onClick prop.

history.goBack lets us go back to the previous page.

In App, we have 2 Links that’s set to go to /foo and /bar respectively.

And we have 2 Routes that’s set to render Foo and Bar when we go to /foo and /bar respectively.

Therefore, when we click on the links and we click Back, we go to the previous page.

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 *