javascriptreactjsreact-routerreact-router-domreact-router-component

How to use optional parameter path for routing


Using React Router Dom V6 Have MainView that has two optional parameter like,

  1. id, this time, "key" is not exist
  2. key, this time, "id" is not exists

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.


Solution

  • 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.