klinore klinore - 1 year ago 183
React JSX Question

Using multiple params with React Router?

<Route path="/:user" component={Home}>
<Route path="/:thing(/:version)" component={Thing}/>

So, I've got two dynamic objects in my application that I'd like to be controlled by route params in react-router. Using the code above, both
take me to
. I need
to take me to
. I'm not sure what I'm doing wrong here... Does react-router even support multiple dynamic params next to each other like this? I couldn't find anything in the docs.

Answer Source

What happens here is that you've given React Router two paths that can both match on /anything. By default then React Router matches the first one it can find.

To dig deeper, if I go to /pudding, React Router can't know if you meant /:user or /:thing. Since /:user occurs first, that option will be chosen.

You also need to make sure if nesting routes is what you want. Currently, your Thing route is nested below Home, which means that it is rendered via this.props.children in your Home component. So, for your current Thing route, Home will always be rendered too, with Thing as a child. If your Home component doesn't render this.props.children, Thing will not be shown.

I suspect you just want two different pages. What you could do to achieve that is the following:

<Router history={history}>
    <Route path="/user/:user" component={Home} />
    <Route path="/:thing(/:version)" component={Thing}/>

This will make every /user/name go to the Home component, and every other /random (with an optional extra level) will go to Thing. If you wonder why in this case React Router doesn't take /user/name to the Thing route, it's because it still matches in the order your routes are specified. Because your Home route matches the requested URL, no siblings of this route are tested anymore.

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