B
B
bormor2018-03-22 19:47:26
React
bormor, 2018-03-22 19:47:26

Nested routes in React Router 4. The 'user1/commit1' link fires the component for 'user1/'. How can this be done properly?

The link '/user1/commit1' triggers the component for '/user1/', not for 'user1/commit1/'
Code snippet:

<Switch>
        <Route exact path="/" component={HomePage} />
        <Route path="/:user" component={UserPage} />
        <Route path="/:user/:commit" component={CommitPage} />
</Switch>

Simple example:
sandbox.io
How can I fix this?
What should be studied in order to understand the issue?

UPD:
First clumsy solution:
<Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/:user" component={UserPage} />
        <Route path="/:user/:commit" component={CommitPage} />
</Switch>

Is this correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-22
@bormor

How can this be fixed?

Add exact - I see that you figured it out yourself. You can also change the order of the routes (the first matching one is rendered):
<Switch>
  <Route exact path="/" component={HomePage} />
  <Route path="/:user/:commit" component={CommitPage} />
  <Route path="/:user" component={UserPage} />
</Switch>

What should be studied in order to understand the issue?

Documentation .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question