'i have a route path where id can be optional how to specify it in routes in react [duplicate]

 <Container>
          <Routes>
          <Route path="/" element={<HomeScreen/>} exact/>
          <Route path="/product/:id" element={<ProductScreen/>}/>
          <Route path="/cart/:id?" element={<CartScreen/>} />
          </Routes>
 </Container>

in the above code for cart screen id parameter is optional it may or may not present so i placed a "?" after id

const addToCart = () => {
      navigate(`/cart/${id}?qty=${qty}`)
 }

when i navigate to /cart/${id}?qty=${qty} i need to go to the CartScreen component how to do it



Solution 1:[1]

One option may be to to define two routes to the same component and then handle in the component weather the parameter exists or not. Like this:

<Route path="/cart/:id" element={<CartScreen />} />
<Route path="/cart/" element={<CartScreen />} />

Though on this post from atomized objects they show this other alternative but not sure if it's compatible with react router v6:

<BrowserRouter>
  <Switch>
    <Route path="/cart/:id?" component={CartScreen} />
  </Switch>
</BrowserRouter>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jcobo1