React nested route page not rendering properly as expected

Viewed 54

I created this react component which has some nested routes. The problem is that the nested page component is either not rendering at all despite the URL changes or just returns a blank page.

I tried the suggestions from other posts like adding/removing exact in the parent route, but it's still not working.

Below are my codes:

// the parent component
<div className="App">
<Router>
        <Navbar />
        <Switch>
         <Route exact path="/" render={() => <MyPage accessToken={accessToken} />}/>
         <Route path="/editing/:playlistId" render={(props) =>
            <EditingPlaylist {...props} accessToken={accessToken} />} />
        </Switch>
</Router>                        
</div>
//the child component EditingPlaylist
render() {

const { pathname } = this.props.location;
return (
    <div className="editing">
        <Switch>
            <Route exact path={pathname} render={() =>
                <Searchbar accessToken={this.props.accessToken} />} />  
            <Route path={`${pathname}/test`} component={<p>Test</p>} />
            <Route path={`${pathname}/album/:albumId`} render={
                (props) => <AlbumPage {...props} accessToken={this.state.accessToken} />} />
            <Route path={`${pathname}/artist/:artistId`} render={
                (props) => <ArtistProfile {...props} accessToken={this.state.accessToken} />} />
        </Switch>
   </div>)
}

export default withRouter(EditingPlaylist);
1 Answers

Use url and path:

const { url, path } = this.props.match

to defined nested routes.

So, in nested routes:

<Switch>
  <Route
    exact
    path={path} // HERE
    render={() => <Searchbar accessToken={this.props.accessToken} />}
  />
  ... 
</Switch>

There is a difference between url and path:

url: It is what is visible in the browser. e.g. /editing/123. This should be used in when redirecting via Link or history.push

path: It is what matched by the Route. e.g. /editing/:playlistId. This should be used when defining (nested) paths using Route.

From docs:

path - (string) The path pattern used to match. Useful for building nested <Route>s

url - (string) The matched portion of the URL. Useful for building nested <Link>s

Related