Noah Noah - 1 year ago 200
React JSX Question

React router v4 wildcard next to index route

Let's say we have this setup

const Parent = () => (
<Switch>
<Route path="/data" component={Child}
</Switch>
)

const Child = () => (
<Switch>
<Route exact path="/" component={SomethingList} />
<Route path="/:id" component={ShowSomething} />
</Switch>
);


When I render parent, I would expect
someUrl/data
to render
SomethingList
and
someUrl/5
to render
ShowSomething
. What actually happens is that both render
ShowSomething
.

How do I get the behavior I'm expecting with react-router v4?

Answer Source

That's because /:id doesn't mean it has to be an integer value. It can be whatever like: /some-path - and id would equal to some-path. That's why you get this behavior.

In your context, the only way to render SomethingList is to use / route. Nothing else will match. I would do it like this:

const Parent = () => (
  <Switch>
    <Route path="/data" component={Child}
  </Switch>
)

const Child = () => (
  <Switch>
    <Route exact path="/data" component={SomethingList} />
    <Route path="/data/:id" component={ShowSomething} />
  </Switch>
);

I guess you think that you can declare relative paths in your child component, which (I think) is not possible with RR4.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download