React router v6.0.0-beta.1 go back / pop history

Viewed 645

I am trying to implement "go back" functionality for a page that could be access from n different urls.

Example, all the following URLs will link to abc.com/b1:

abc.com/a1
abc.com/a2
abc.com/a3
abc.com/a4
...
abc.com/an

From abc.com/b1 I want to support a link that takes you back to the previous page you visited.

My first attempt is to use:

...

const navigate = useNavigate();
navigate(-1);

...

However, if you land straight in abc.com/b1 navigate(-1) will likely take you outside of my application into some other site, or browser about:blank.

What is the best approach to implement such functionality?

  • is there a way to access the history length to check wether we should navigate(-1) or push a new page?
  • should I pass additional state/query from a pages to b? so b knows how to go back? this seems like overkill.

Thanks.

1 Answers

I was with the same problem, but I finally found a solution that worked for me.

I'm using the react-router-dom@6.2.1.

// Simply return to the previous page or to the initial route
navigate('..')
Related