I’m using React Router v5, and I wonder how can I match all children of /add
but /add/..
in one path. For example /add_a
,/add
, /add123
etc.
I’ve tried <Route path="/add*" element={<div>TEST</div>} />
, but I got a warn that Route path "/add*" will be treated as if it were "/add/*"
.
<Routes>
<Route path="/add*" element={<div>TEST</div>} />
</Routes>
reference:
https://v5.reactrouter.com/web/api/Route/path-string-string
2
Answers
Try this
/add[^/]+
this will match all but except the second "/"This means
/add_somethinghere
is matchesbut
/add_somethinghere/extrathing
is not matchTry the playground here https://forbeslindesay.github.io/express-route-tester/
You are actually using React-Router v6 according to the code and warning. React-Router v6 removed path regular expressions. You can read more about it in "What Happened to Regexp Routes Paths?".
I suggest you use route path
"/:add/*"
and regular expression/^add.*$/
to:add
parameter"*"
to allow descendent route matchingadd
parameter value in the routed component and conditionally redirect/render the specific contentExample:
If you intended to use React-Router v5 then ensure you have the proper version installed:
And use the correct components and API: