0
 <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

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
kichu
  • 121
  • 1
  • 1
  • 11

1 Answers1

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>
jcobo1
  • 1,065
  • 1
  • 18
  • 34