K.Nicholas
K.Nicholas

Reputation: 11561

React route with exact path and param troubles

I have a react Route path with params but it always matches even though I use exact on the Route.

    <Route exact path="/:term?" component={Home} />
    <Route path="/some" component={SomePage} />

If I nav to / then ok, no problem. If I nav to /some then I get both components rendered.

How do I prevent both components from being rendered for the second path?

A Codebox Example

EDIT: With <Switch> then the above example never routes to the /some path.

Upvotes: 1

Views: 813

Answers (3)

zx01
zx01

Reputation: 571

I hope this works.

<Router>
    <Switch>
        <Route exact path="/some" component={SomePage} />
        <Route exact path="/:term?" component={Home} />
    </Switch>
</Router>

Upvotes: 0

Robinson De La Cruz
Robinson De La Cruz

Reputation: 156

If the URL is /some, then and will all render because they all match the path. We want to pick only one to render. If we’re at /some we don’t want to also match /:term?. Here’s how to do it with Switch:

<Router>
  <Switch>
    <Route path="/some" component={SomePage} />
    <Route exact path="/:term?" component={Home} />
  </Switch>
</Router>

Upvotes: 1

andy mccullough
andy mccullough

Reputation: 9611

Be sure you have wrapped your Route components in a Switch component, so that only one of the routes gets used.

https://reactrouter.com/web/api/Switch

Upvotes: 3

Related Questions