How can I override react-router-dom Link component back link?

Viewed 591

For what it's worth this is for react-router-dom v5.2.0.

I used to be able to easily override the back button link with the following code:

const MyLink = () => ({
    <Link
        to={{
            pathname: 'go-somewhere',
            state: { previousPath: 'override-previous-path'
        }}
    >
        Go Somewhere
    </Link>
})

By setting previousPath to whatever I would like to override to, it would override whatever I had visited previously. However, now that simply seemed to have stopped working one day.

Looking at the docs the to prop does not seem to have been changed, but the location has. Is it the previousPath state property that is incorrect?

Is there still a way to override the back link through the Link component?

1 Answers

Based on what we have discussed in the question comments, it doesn't seem possible to replace the current entry in the history stack by simply setting a previousPath on the state property (at least in react-router-dom v5.2.0).

An alternative solution could be something like this:

import { useHistory, Link } from "react-router-dom";

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

  return (
    <Link to="go-somewhere" onClick={() => history.replace("override-previous-path")}>
      Go Somewhere
    </Link>
  );
};

This will take the user to where you want him to go and it will replace the current entry in the history stack with the route that you want. So... if a .goBack() or a .go(-1) is executed, it will take the user "back" to where you wanted instead of the previous page.

Related