How to Make React Router Resolve within a nested path

I’m a little bit uncertain as to what might be wrong here.

I have a React router switch that is nested within another React Router switch as below

Switch in homepage.js file is as below

<Switch>
       <Route path={HomePageRoutes.CONTENTS}> //which is just /contents
         <ContentPage initialData={fetchedData}/>
       <Route>
       <Route path={HomePageRoutes.ADS}>
         <AdsPage/>
       </Route>
</Switch>
         

Now, ContentPage which was referenced above is in a file called contentpage.js and that page also contains a switch as below:

export default function ContentPage(){
 ......
     <Switch>
        <Route path={`/first`}>
             <FirstContentPage/>
        </Route>
        <Route>
            <DefaultContentPage/>
        </Route>
     </Switch>
 ......
}                       

I was expecting that if the current location in the browser is at say /content and I click on a link that redirects to /first, the /first will be appended to the current location to become /content/first and the FirstContentPage component should render but unfortunately it is not rendering?

What am I doing wrong?

Thanks in anticipation for your input.

Answer

You will need to access the current path from the match prop. Since ContentPage is not receiving route props you may need to wrap ContentPage in the withRouter Higher Order Component.

match

A match object contains information about how a <Route path> matched the URL. match objects contain the following properties:

  • params – (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact – (boolean) true if the entire URL was matched (no trailing characters)
  • 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
function ContentPage({ match }) {
  const { path } = match;

  ......
    <Switch>
      <Route path={`${path}/first`}>
        <FirstContentPage/>
      </Route>
      <Route>
        <DefaultContentPage/>
      </Route>
    </Switch>
  ......
}

export default withRouter(ContentPage);