I was trying to get back to react-router-dom Route handling and found a use case that I’m not able to get around. Here’s the summary of it.
I was thinking of creating a URL route like this : http://localhost:3001/org/:area?/:id/:tabId?
.
<Route exact path='/org/:area?/:id/:tabId?'>
...
</Route>
When I am visiting the below urls, the dymamic values are not matching what I would want them to be.
-
http://localhost:3001/org/e439e39b-1974-4934-8570-a1bf68211a0d
:area = e439e39b-1974-4934-8570-a1bf68211a0d
-
http://localhost:3001/org/e439e39b-1974-4934-8570-a1bf68211a0d/XYinx
:area = e439e39b-1974-4934-8570-a1bf68211a0d
:id = XYinx
-
http://localhost:3001/org/shop/e439e39b-1974-4934-8570-a1bf68211a0d
:area = shop
:id = e439e39b-1974-4934-8570-a1bf68211a0d
-
http://localhost:3001/org/shop/e439e39b-1974-4934-8570-a1bf68211a0d/XYinx
:area = shop
:id = e439e39b-1974-4934-8570-a1bf68211a0d
:tabId = XYinx
Some contraints to the above route are:
a. "e439e39b-1974-4934-8570-a1bf68211a0d" has to be treated as :id in the url
b. "shop" has to be treated as :area
c. "XYinx" has to be treated as :tabId
Here as you see 1st and 2nd URLs are problematic as per this url structure. I also tried separating the two like this:
<Route exact path="/org/:area/:id/:tabId?">
...
</Route>
<Route exact path="/org/:id/:tabId?"}>
...
</Route>
but again here the problem is that the 2nd route will match the 1st URL as well. Do you guys have a better idea on how to handle this? Any help here would be appreciated. Thanks in advance.
Note: I am using v5 of react-router-dom and v17 for react.
2
Answers
According to https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters you can pass provide a regex for your match parameters.
It means that you should be able to do something like that:
because both paths have dynamic params under the same path "/org", then it will always go for the first one.
in that case, you will want to add a static param that will help identify the path.
here is an example of some options you can use: