Reputation: 9881
I am using React Router v6.4.1 and would like to have a consistent ending to a set of dynamic routes.
For instance, I would like my product detail routes to ends with "-product".
Say I have a path like "/shaver-900-product". This should trigger my ProductDetails
component which could then use "shaver-900" to get the product details from my API.
I've tried defining the path using the following, but I cannot get this working:
<Route path=":productSlug-product" element={<ProductDetails />} />
If the product slug in the API/Database changes to have "-product", then this would work:
<Route path=":productSlug" element={<ProductDetails />} />
However, I would prefer to not change the database and only make the changes to how the routes are matched.
Upvotes: 1
Views: 384
Reputation: 202854
react-router-dom@6
route paths no longer handle any sort of regex patterns for path matching, the path parameters are effectively all or nothing. Use the productSlug
param and handle the string manipulation in the matched routed component.
<Route path=":productSlug" element={<ProductDetails />} />
Path is "/shaver-900-product"
.
const ProductDetails = () => {
const { productSlug } = useLocation();
... logic to extract "shaver-900" from productSlug ...
...
};
Upvotes: 1