Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

optional /id?/ parameter in React Route path not working

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading