Search code examples
reactjsreact-routerreact-router-dom

An I use an element attribute on a Route component so that the ID is not necessary?


App.jsx

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

In React-router-v6 can I still use this so that the id parameter is not always necessary?
if it exists it goes to the "CartScreen" component
if it doesn't exist it also goes to the "CartScreen"


Solution

  • React Router v6.5+

    Yes, the above code will work. Although not originally supported in version 6, it has been reintroduced in recent updates.

    React Router v6.0-6.4

    Optional params are not supported. Instead, you must create two separate routes:

    <Route path="/cart/" [...]>
    <Route path="/cart/:id" [...]>