简体   繁体   中英

Custom dynamic routes using react-router

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 ?

Standard routing

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.

Ref: https://github.com/reacttraining/react-router/tree/master/packages/react-router-config#route-configuration-shape

if you have conflict with static routes place the dynamic route last in route scaffolding

Ref: https://tylermcginnis.com/react-router-ambiguous-matches/

Custom route formats

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

Screenshot from route tester

在此输入图像描述 Ref: https://github.com/ReactTraining/react-router/issues/5536#issuecomment-330548834

Route tester: https://pshrmn.github.io/route-tester/#/def-abc-xyz-12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM