I have two navigation menu, Artists and Albums on menu bar. I am using react_rotuer_dom v6
Here is the nested navigation structure.
- Click Artists (Artist list will show) /artists
- Click Artist (Album list will show) /artists/artist/xxx
- Click Album (Track list will show. /artists/artist/xxx/album/yyy
- Click Track (show lyric). /artists/artist/xxx/album/yyy/track/zzz
So far my nested route is working as expected. Now I want to go back to Album(3) from Track(4). There is a link Album to navigate back to Album. So how can I navigate this path /artists/artist/xxx/album/yyy from Track page. I can give absolute path /artists/artist/xxx/album/yyy, it is working.
But What if I click Albums route. I am using same pages for Albums, Album, and Track. Please see my rote below. Am I using correct way for nested route.
path
const paths = {
home: "/",
artists: "/artists",
getArtists: () => `/artists`,
artist: "artist/:artistId",
getArtist : (artistId) => `artist/${artistId}`,
albums: "/albums",
getAlbums: () => `/albums`,
album: "album/:albumId",
getAlbum: (albumId) => `album/${albumId}`,
track: "track/:trackId",
getTrack: (trackId) => `track/${trackId}`,
};
export default paths;
Routes
<Routes>
<Route path={paths.home} element={<HomePage />}></Route>
<Route path={paths.artists}>
<Route index element={<ArtistsPage />} />
<Route path={paths.artist}>
<Route index element={<AlbumsPage />} />
<Route path={paths.album}>
<Route index element={<AlbumPage />} />
<Route path={paths.track} element={<TrackPage />}></Route>
</Route>
</Route>
</Route>
<Route path={paths.albums}>
<Route index element={<AlbumsPage />} />
<Route path={paths.album}>
<Route index element={<AlbumPage />} />
<Route path={paths.track} element={<TrackPage />}></Route>
</Route>
</Route>
</Routes>
CodePudding user response:
If I'm understanding your question correctly you are asking how to navigate back to a parent route dynamically.
Just like the routes use relative paths to build up the route tree structure, the links can also use relative paths for linking.
A relative
<Link to>
value (that does not begin with/
) resolves relative to the parent route, which means that it builds upon the URL path that was matched by the route that rendered that<Link>
. It may contain..
to link to routes further up the hierarchy. In these cases,..
works exactly like the command-linecd
function; each..
removes one segment of the parent path.
To navigate back two path segments to get from a specific track back to a specific album, use ../..
.
Example:
<Link to="../..">Back to parent</Link>
If the path is "/artists/artist/xxx/album/yyy/track/zzz"
then clicking the link will navigate "up/back" two path segments to "/artists/artist/xxx/album/yyy"
. Similarly, if the path is "/artists/artist/xxx/album/yyy"
then clicking the same link will again navigate "up/back" two path segments to "/artists/artist/xxx"
.