Home > Blockchain >  React Router — Go back using <Link>
React Router — Go back using <Link>

Time:06-19

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

CodePudding user response:

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

CodePudding user response:

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