How to render nested routes with multiple optional params and path placeholders?

839 views Asked by At

I've been trying to use react-router to define a series of nested components/routes w/ optional params, but also separated by path placeholders.

i.e.

/list
/list/1
/list/items
/list/1/items
/list/1/items/1

I would assume the two <Route> paths would be something like:

/list/:listId?
and
`${match.url}`/items/:itemId?`

But alas.. "items" always ends up being accepted as the listId param, and therefore, the sub-routing for /items never matches.

I have a generic example I've coded here (doesn't accomplish a solution): https://stackblitz.com/edit/nesting-w-optional-params-react-router

I see examples all over the internet for /root/:id1?/:id2? but nothing for what I'm trying to do where I have a placeholder between the params: /root/:id1/placeholder/:id2.

Is this possible to do w/ react-router v4+ ??

1

There are 1 answers

0
RavenHursT On

Figured out a solution utilizing RR's children pattern, to always render the nested route/component, but then inside the component use path-to-regexp directly to do route matching and to grab relevant route params from props.location.pathname.

Relevant bit of code:

render() {
    const pathRe = new PathToRegexp('/foo/:fooId?/bar/:barId?')
    const match = pathRe.match(this.props.location.pathname)
    if (!match) {
      return null
    }
    const barId = (this.props.match && this.props.match.params.barId) || match.barId
    return <h1>Bar <em>{barId}</em></h1>
  }

https://stackblitz.com/edit/nesting-w-optional-params-react-router-solution