Sometimes you need an optional parameter in the URL, so React will render a component even if certain part of the URL is ‘missing’.
Specific Examples
Add optional parameter in react-router
To define any path, you need to import a custom <Route> component from react-router library, and have necessary environment (<BrowserRouter>) to use it.
Set path attribute of a Route component to a string that tells React what components to render depending on current URL.
Optional Params in React – Example
In react router, optional parameters are defined using a question mark. Keep in mind that question mark needs to be added at the end.
<Route path="/cart/:productId?" element={<ShoppingCart />} />
In this case, the ShoppingCart component will be rendered if the URL matches /cart/ path, as well as if the URL has additional productid parameter.
This simple and easy-to-understand syntax is compatible with react-router versions above 4, with few exceptions*.
Now, let’s see how to define optional parameter using react router versions that do not support this syntax.
If your version of react-router does not support optional params
Versions earlier than react router v4 and releases between 6 and 6.4.5 do not support using a question mark to add optional params to the URL.
The solution is to write two paths, one that includes optional parameter, and one that doesn’t.
<Route path="/cart/:productId" element={< ShoppingCart />} />
<Route path="/cart/" element={< ShoppingCart />} />
This approach takes more lines of code, but accomplishes the same as using the question mark. So technically, the only difference is conciseness of code.