Using React Router Dom V6 Have MainView that has two optional parameter like,
Both paths points to same view, just need key or id distinguish params
Trying to achieve using below way but, it does not fall under 'key' path.
So, while using, const {id, key} = useParams();
key remains undefined.
<Routes>
<Route path="/mainview">
<Route path="/id" element={<MainView />} />
<Route path="/key" element={<MainView />} />
</Route>
</Routes>
Could you please guide how can it be achieve so, either of path can be supported.
You are not actually assigning a dynamic path segment. You should name the path parameter. Since both "/:id?"
and "/:key?"
would resolve to the same path for matching, only one route will work.
Example:
<Routes>
<Route path="/mainview">
<Route path=":id?" element={<MainView />} />
</Route>
</Routes>
const { id } = useParams();
Please also note that optional path parameters were only reintroduced into react-router
in v6.5, so if you are actually needing optional path params you'll need to ensure you are on react-router@6.5
or later.