2

So All the components are rendering fine on new page except the nested route ones. Also the url changes but the component renders on the same page after all the components of previous page instead of rending on its own page. here is the code

App.js

function App() {
  return (
    <PlaylistState>
      <Router>
        <div className="App">
          <Navigation />
          <main className="content-container">
            <Switch>
              <Route exact path="/">
                <Home />
              </Route>
              <Route exact path="/favourites">
                <Favourites />
              </Route>
              <Route exact path="/playlistForm">
                <PlaylistForm />
              </Route>
              <Route path="/playlists">
                <Library />
              </Route>
            </Switch>
          </main>
        </div>
      </Router>
    </PlaylistState>
  );
}

export default App;

Library.js

const Library = () => {
  return (
    <div>
      <h1 className="my-2">Library</h1>
      <Playlists />
    </div>
  );
};

export default Library;

Playlists.js

const Playlists = () => {
  const PlaylistContext = useContext(playlistContext);
  const { playlists } = PlaylistContext;
  const { url, path } = useRouteMatch();

  // console.log(url);
  console.log("path", path);

  return (
    <section className="playlist-container">
      {playlists.map((playlist) => (
        <>
          <Link to={`${url}/${playlist.id}`}>
            <PlaylistCard key={playlist.id} cardDetails={playlist} />
          </Link>
        </>
      ))}

      <Route path={`${path}/:playlistId`}>
        <Playlist />
      </Route>
    </section>
  );
};

export default Playlists;

1 Answers1

1

That's the expected behavior of a nested route, it renders inside the parent component, see this question.

If you want the route "/playlists/:playlistId" to render only <Playlist />, you should have at the top level as a sibling to all the other routes.

EDIT: code

    function App() {
      return (
        <PlaylistState>
          <Router>
            <div className="App">
              <Navigation />
              <main className="content-container">
                <Switch>
                  ...
                  <Route path="/playlists/:id">
                    <Playlist />
                  </Route>
                  <Route path="/playlists">
                    <Library />
                  </Route>
                </Switch>
              </main>
            </div>
          </Router>
        </PlaylistState>
      );
    }

export default App;

Iman
  • 26
  • 1
  • 3