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>
I don't know what URL to pass to the Link.
Why is it important: Changing it to <Link>
would allow 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). For example, it allows users to:
- right-click and open the page in a new tab.
- when it's the first opened page, the "back" does not work at all, while the link works always.
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
Update 3: I've added my own answer below.