skip to Main Content

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


  1. 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:

      const { productSlug } = useParams();
      const [category, product] = productSlug.split("--");
    

    I hope this clears your doubts

    For your reference: React Router

    Login or Signup to reply.
  2. Partial path matches are not allowed in React-Router 6.

    You can either make the city a separate segment (recommended):

    path="/property-in/:cityName"
    

    Or make the entire segment dynamic and parse the segment in the component:

    path="/:propertyInCity" // "/property-in-newyork"
    
    const { propertyInCity } = useParams();
    const [,,city] = propertyInCity.split("-"); // ["property", "in", "newyork"]
    

    See Dynamic Segments for complete details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search