Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional /id?/ parameter in React Route path not working [duplicate]

I am learning react and I saw a video and the where using a question mark for an optional id parameter passed in the URL path like this

<Route path='/cart/:id?' element={< CartScreen />} exact/> 

the ? next to id is not supposed to be taken as parameter in the URL The video I saw is from two years and i am using a newer react version I tried to search for the solution but no luck

like image 545
bysEcode Avatar asked Nov 21 '25 15:11

bysEcode


1 Answers

It depends on which version of the react router you're using.

For V1, V2 and V3 optional parameters can be defined as:

<Route path='/cart(/:id)' element={< CartScreen />} exact/>

For React Router V4,V5 you can use:

<Route path='/cart/:id?' element={< CartScreen />} exact/> 

As for React Router V6, it no longer supports optional routes but instead opts for nested Routes.

<Route path="/page/:friendlyName">
  <Route path=":sort" element={<Page />} />
  <Route path="" element={<Page />} />
</Route>

Official docs for changes going from V5 to V6. See the relative links section for more information.

like image 197
Ryhazerus Avatar answered Nov 24 '25 06:11

Ryhazerus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!