React Router — Go back using <Link>

Viewed 461

In React Router v6, how can I go back to the previous page using <Link> instead of useNavigate().

// Instead of this...
<button onClick={() => navigate(-1)}>
// ...it needs to be this:
const previousPage = ???

<Link to={previousPage}>Go back</Link>

This behavior change allows me to use <a href="xxxx"> instead of a <button>, which is the most accessible way of creating links between pages. (More about button vs links)

Update: I've created a codesandbox to help you find the solution.

Update 2: Based on the answers and some research, I created a GitHub issue to react-router

3 Answers

It's not a bug in react-router-dom@6 and not really anything a Link is meant to do, i.e. it's just an anchor tag under the hood, and links to a path as a declarative navigation action. This is fundamentally different than an imperative action like history.go(1) or history.back() (i.e. history.go(-1)) where you are imperatively saying to navigate forward/backward through the history stack.

In react-router-dom@6, however, you can navigate relative to the current path. ".." will navigate "back" one path segment for any Route components rendered within the current Routes component. I.E. from "/destiny" back to "/" with the same Routes component.

Example:

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

export default function Destiny() {
  return (
    <div>
      <h1>Destiny Page</h1>
      <Link to={'..'}>Go back</Link>
      <br />
      <Link to="/">Go Home ("/")</Link>
    </div>
  );
}

Note that this isn't the equivalent of navigate(-1) as it isn't transitioning through the history stack, so it's not a true back navigation. If you want to do a true back navigation then you'll want to add an onClick handler to the Link and prevent the default event action and handle issuing an imperative back navigation.

Example:

import { useNavigate, Link } from 'react-router-dom';

export default function Destiny() {
  const navigate = useNavigate();

  return (
    <div>
      <h1>Destiny Page</h1>
      <Link
        to={'..'}
        onClick={(e) => {
          e.preventDefault();
          navigate(-1);
        }}
      >
        Go back (-1)
      </Link>
      <br />
      <Link to="/">Go Home ("/")</Link>
    </div>
  );
}

Edit react-router-go-back-using-link

<Link to={-1}>Go Back</Link> will work.

This might work...

let url = '\\peviouspagename.js';
let element = <Link to={url}>Go Back</Link>

Place anywhere before your function...

In the function, you'll have something like: <div>{element}</div> where the script is normally to go. Element is the <Link> script. State the URL separate, the page name is all it needs. You can hash <div id="hash"></div> as well by adding it to to the end like so: let url = '\\peviouspagename.js#hash'; doing so should take you directly to the that <div> onClick.

Related