9

Surprisingly that it's been kind of hard to find in Google and in StackOverflow, I'm asking here what's the most efficient way on going up one level in React Router using <Link>?

For example I land in this path: /subject/add. Then I want to go to /subject from /subject/add.

This works:

<Link to={props.match.url.substring(0, props.match.url.lastIndexOf('/'))}>
Go up one level </Link>

Is it the best way to do it? (Note: history.goBack could potentially kick out the user from the website if he arrived on a nested route as his landing page.

Jose A
  • 10,053
  • 11
  • 75
  • 108
  • I think that you can use the push('/subject') method to achieve that. – Cyro Apr 25 '19 at 22:03
  • 2
    If you want to have the exact same `` that will go "up a level" no matter where it is then I think your method is fine. – jered Apr 25 '19 at 23:22
  • sorry for the silly question but what's that "props" that you are referring in your Link component? because I'm getting 'not defined' error. – Shayan de Apr 23 '20 at 20:15
  • 1
    @Shayande Props would be the RouteComponentProps that comes from the component's props. In case of React-Router check this out: https://stackoverflow.com/questions/51523211/react-routing-using-routecomponentprops-and-custom-props – Jose A Apr 24 '20 at 03:56

2 Answers2

10

If somebody still needs it - there is a solution from authors: You can use "." or ".." in your Link component to go one or two levels up.

<Link to=".">

or

history.push(".");
Yevgeniy Timchenko
  • 360
  • 1
  • 3
  • 11
2

This worked for me:

<Link to=".." relative="path">

https://reactrouter.com/en/main/components/link#relative

Moose
  • 21
  • 1