Here’s a routes I have created so far.
<BrowserRouter>
<Routes>
<Route path="/" exact element={<FrontPage />} />
<Route path="/property-in-:cityName/" element={<PropertyListing />} />
<Route
path="/property-in-:cityName/:singlePropertySlug"
element={<PropertySingle />}
/>
<Route path="/associates" element={<AssociateListing />} />
<Route path="/about-us" element={<AboutUs />} />
<Route path="/contact-us" element={<ContactUs />} />
<Route path="/*" element={<PageNotFound />} />
</Routes>
</BrowserRouter>
Is there any way to achieve a partial dynamic route in React-Router-DOM where "/property-in-"
will be static and ":city"
will be dynamic?
I tried the above method of route but it’s not working. When I enter "/property-in-newyork/"
it gives me 404 but when I type "/property-in-:cityName/"
this exact route it loads the component. When I try to grab that parameter using the following method in <PropertyListing />
the component it gives me an undefined error in the console.
const { cityName } = useParams();
console.log("City:", cityName);
2
Answers
Dynamic segments cannot be "partial":
🚫"/teams-:teamId"
✅ "/teams/:teamId"
🚫 "/:category--:productId"
✅ "/:productSlug"
However, you can create your own way of handling it
For something like
"/:category--:productId"
you can do:I hope this clears your doubts
For your reference: React Router
Partial path matches are not allowed in React-Router 6.
You can either make the city a separate segment (recommended):
Or make the entire segment dynamic and parse the segment in the component:
See Dynamic Segments for complete details.