Home > other >  Reactjs nested routes is not redirect to child screen
Reactjs nested routes is not redirect to child screen

Time:02-17

At menu, I have Albums. If user click the Albums, AlbumsPage(All of Album) will show. If user click the Album, AlbumPage will show. So I want my Albums menu is still selected.

But If I click Album, route is not working. Still showing AlbumsPage. I don't see no error. What is wrong with my nested route?

Paths

const paths = {
  home: "/",

  albums: "/albums",
  getAlbums: () => `/albums`,
  album: "album/:albumId",
  getAlbum: (albumId) => `album/${albumId}`,
};

export default paths;

Rotes

  <Routes>
    <Route path={paths.albums} element={<AlbumsPage />}>
      <Route path={paths.album} element={<AlbumPage />}></Route>
    </Route>
  </Routes>

CodePudding user response:

If I understand your question correctly you want:

  1. AlbumsPage to be rendered exclusively on path="/albums"
  2. AlbumPage to be rendered exclusively on path="/albums/album/###"

You can move AlbumsPage into an index route so that is it matched and rendered when the parent Route component's path is exactly paths.albums, or "/albums". AlbumPage will continue to be rendered on the relative path paths.album, or resolved as "/albums/album/###". By not specifying an element prop for the parent Route an Outlet component will be rendered by default for the nested Route components to be rendered into.

<Routes>
  <Route path={paths.albums}>                            // "/albums" `Outlet` is rendered
    <Route index element={<AlbumsPage />} />             // "/albums"
    <Route path={paths.album} element={<AlbumPage />} /> // "/albums/album/###"
  </Route>
</Routes>
  • Related