3

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

3
  • RRDv6 removed support for Regular Expressions, so optional parameters are no longer supported. See duplicate for examples utilizing explicit routes. Oddly enough, the code in the duplicate uses an identical path. Possibly code from a code academy project/assignment, or referencing the same tutorial? Commented Aug 2, 2022 at 21:24
  • 1
    why would they do that, i realised v 4 and 5 is better than 6 but i am already half way throught :( Commented Aug 2, 2022 at 21:34
  • I think once you get used to v6 and use it more you might just realize how good an update it is. Sure, some things were dropped, but they got a lot right and fixed a lot of v5's shortcomings. Commented Aug 2, 2022 at 21:35

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.