Reputation: 124
There is little unconventional routes requirement for a project i am working on. The route has following structure /<--name-->-abc-xyz-<--id-->
where name and id are dynamic. Now i want to match this route using react router. So i did the following
<Route path='/:name-abc-xyz-:id' component={View} />
This fails for the cases where name name is of this form def-abc-xyz-*.
How to fix this such that i get value of name and id in View component directly.
I have a workaround where i do
<Route path='/:dynamicId' component={View} />
and now i parse dynamicId and take out name and id from it in my View compoenent. Is there a way to achieve the following without parsing ?
Upvotes: 3
Views: 606
Reputation: 15821
The standard way how this is managed in V4 is to provide a route in config as:
/:name/abc-xyz/:id
If you are not constrained by another parser to use the above dashed-schema this solution will fit your needs.
if you have conflict with static routes place the dynamic route last in route scaffolding
Ref: https://tylermcginnis.com/react-router-ambiguous-matches/
Additionaly, notice
React Router uses path-to-regexp for its route matching.
This means that if you provide a route in this format:
/:name(\w+-)?abc-xyz(\w+-)?:id
This will work too while comparing (IE)
def-abc-xyz-12
Ref: https://github.com/ReactTraining/react-router/issues/5536#issuecomment-330548834
Route tester: https://pshrmn.github.io/route-tester/#/def-abc-xyz-12
Upvotes: 2