I have some nested routes, and I need to navigate back "a level up" so to say.
I'm using react-router-dom v5.3.1
history.goBack() will take me to last visited page, as if I use the back button in the browser. I don't need this.
Imagine my history looks something like this...:
[
dashboard/1/sub-page/7
dashboard/1/sub-page/13
dashboard/1/sub-page/9
dashboard/1/sub-page/1
]
My browser URL is: localhost:8080&app.html#/dashboard/1/sub-page/7
Does react-router-dom provide a safe way for navigating to: localhost:8080&app.html#/dashboard/1 - or what would be a decent approach here?
The history object can only navigate to specifically defined paths via a path string with .push/.replace, or navigate forward/backward via a delta with .go.
You can create a "goToParent" handler that reads the current matched location's pathname and slice off the last path segment and issue a PUSH.
Example:
import { useLocation, useHistory } from "react-router-dom";
...
const { pathname } = useLocation();
const history = useHistory();
const goUpLevel = () => {
const parent = pathname.split("/").slice(0, -1).join("/");
history.push(parent);
}
If you wanted to go two levels up, i.e. from "/dashboard/1/sub-page/7" to "/dashboard/1" then use .slice(0, -2) to slice off the last two segments.
You can use "." or ".." in your Link component to go one or two levels up.
<Link to=".">Go one level up</Link>
<Link to="..">Go two levels up</Link>
Another approach is to map routes into helpers so you can reutilize them all along the codebase:
// Routes helpers
const dashboardRoute = (id) => `/dashboard/${id}`;
const subPageRoute = (id, subId) => `/dashboard/${id}/sub-page/${subId}`;
// Routes mapping
<Switch>
<Route path={dashboardRoute(":id")}>
<Dashboard />
</Route>
<Route path={subPageRoute(":id", ":subId")}>
<SubPage/>
</Route>
</Switch>
// Route helper usage
<Link to={dashboardRoute(id)} >Go to dashboard route</Link>