How can sub paths be defined by omitting the parent path with React-Router-Dom?

Viewed 423

So, let's say I have Profile page which renders different components according to the path. For example:

/profile/posts renders Posts component inside Profile.

/profile/comments renders Comments component inside Profile.

I normally first render Profile page for "/profile" path and then inside it, render relevant Component according to the Routes mentioned above. What I would like to do is, omit the "/profile" part of the paths defined in Route components inside Profile and only keep the remaining part. How can that be done by not breaking the routing ?

See the comments in the code below:

// App.js

// ...

<Switch>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="/profile">  // Profile page is rendered here
      <Profile />
    </Route>
</Switch>

// ...
// Profile.js

// ...

<Switch>
    <Route exact path="/profile/posts">  // I want to omit "/profile" part of the path.
      <Posts />
    </Route>
    <Route path="/profile/comments">  // I want to omit "/profile" part of the path.
      <Comments />
    </Route>
</Switch>
// ...
1 Answers

When nesting routes if you don't want to "duplicate" path details then you can get them from the match object, specifically the path value for building nested routes.

Assuming Profile is a function component, use the useRouteMatch hook to access the currently matched route's path value. If it is a class component then it will have to access route props to get this.props.match.

// Profile.js

const { path } = useRouteMatch();

// ...

<Switch>
  <Route path={`${path}/posts`}> 
    <Posts />
  </Route>
  <Route path={`${path}/comments`}>
    <Comments />
  </Route>
</Switch>

// ...

Here's a more in-depth nested routing demo from `react-router-dom.

Related