0

I have two kinds of routes: a user and a project route. The user route is a top-level URL resource, while project belongs to a user. For example: /users/1/foo and /users/1/projects/2/bar.

I want to show a component specific to a user route only when the route doesn't contain /projects/:id, and project-specific component whenever it does.

Trying the following will in both cases load the /users/:id route:

<Switch>
  <Route path="/users/:id" component={...} />
  <Route path="/users/:id/projects/:projectId" component={...} />
</Switch>

<Switch>
  <Route path="/users/:id/projects/:projectId" component={...} />
  <Route path="/users/:id" component={...} />
</Switch>

Normally, this could be achieved very easily by having a component with a conditional showing either component, however my requirement is that I want to load the user- and project-specific components dynamically (the imports being handled by webpack and react-loadable automatically), so it looks like I'd need a Route-level solution, or perhaps something custom using react-loadable.

EDIT The issue was that I was specifying the wrong path for the Route. Doing what I wanted is possible as long as I put the more specific (project) route first inside a <Switch />

Maciej Gurban
  • 5,615
  • 4
  • 40
  • 55

1 Answers1

1

What you're looking for is exact.

<Switch>
    <Route exact path="/users/:id" component={...} />
    <Route exact path="/users/:id/projects/:projectId" component={...} />
</Switch>

From the v4 docs.

  • Hi! The exact won't work for me, because my routes can be `/users/1/foo` or `/users/1/bar` - and in that case the component should show as well. I actually figured out the that config I showed in my question would work. I was simply specifying the wrong path and will need to place the more specific route first. Cheers! – Maciej Gurban Jul 27 '18 at 12:43