Reputation: 35805
This Stack Overflow question/answer explains how to define React Router (v4) routes which contain multiple optional parameter, eg.:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
However, it doesn't explain how to put optional text in-between those parameters, for instance:
<Route path="/to/page/:pathParam1?/otherParam/:pathParam2?" component={MyPage} />
// Should match /to/page/1 AND /to/page/1/otherParam/2
This was certainly possible in previous versions of React Router, but I can't see how to do it in the current version. Is there any way to specify optional parameter/non-parameter pairings, or even just optional non-parameters? Something like:
<Route path="/to/page/:pathParam1?/(otherParam/:pathParam2?)" component={MyPage} />
Upvotes: 0
Views: 601
Reputation: 9165
React router uses path-to-regexp
- https://github.com/pillarjs/path-to-regexp
You can match optional non-parameters with a path like this:
const path = "/to/page/:pathParam1?/(otherParam)?/:pathParam2?"
And to test it:
const re = pathToRegexp(path)
console.log(re.exec("/to/page/1"))
// ["/to/page/1", "1", undefined, undefined]
console.log(re.exec("/to/page/1/otherParam/2"))
// ["/to/page/1/otherParam/2", "1", "otherParam", "2"]
Upvotes: 2