Shh
Shh

Reputation: 309

react-router-dom - add param to index url but accept page

Currently I have the following code:

<Router history={history}>
  <div>
    <Route exact path="/:id?" component={Container1} />
    <Route path="/component2/ component={Container2} />
  </div>
</Router>

"localhost:3000" returns Container 1 (as expected).

"localhost:3000/123" returns a different view of Container 1 (as expected).

However when I navigate to "localhost:3000/component2/" it appears along side Component 1.

My question is how can I make the index route take both an id but still accept a component?

Upvotes: 0

Views: 464

Answers (2)

Andrew Miroshnichenko
Andrew Miroshnichenko

Reputation: 2074

You can try to wrap these two routes in Switch, like this:

<Router history={history}>
  <div>
    <Switch>
      <Route path="/component2/" component={Container2} />
      <Route exact path="/:id?" component={Container1} />
    </Switch>
  </div>
</Router>

Upvotes: 2

peetya
peetya

Reputation: 3628

React Router handles the routes with the same priorities as in which order did they get defined. So in your case it should be

<Router history={history}>
  <div>
    <Route path="/component2/ component={Container2} />
    <Route exact path="/:id?" component={Container1} />
  </div>
</Router>

Upvotes: 1

Related Questions