Home > Software design >  React router : how can I combine those routes into a single one?
React router : how can I combine those routes into a single one?

Time:05-31

I have those routes

    <Route path="/carte/:mapPostId/:mapPostSlug" element={<SingleMapPage/>} />
    <Route path="/carte/:mapPostId/:mapPostSlug/:urlSourceId/:urlFeatureId" element={<SingleMapPage/>} />
    <Route path="/carte/:mapPostId/:mapPostSlug/:urlSourceId/:urlFeatureId/:urlFeatureAction?" element={<SingleMapPage/>} />

All of them are working.

I thought I could combine them into a single one like

    <Route path="/carte/:mapPostId/:mapPostSlug/:urlSourceId?/:urlFeatureId?/:urlFeatureAction?" element={<SingleMapPage/>} />

But that does not work at all.

What am I doing wrong ?

Thanks !

CodePudding user response:

<Route path="/carte/:mapPostId/:mapPostSlug/:urlSourceId/:urlFeatureId/:urlFeatureAction?" element={<SingleMapPage/>} />

CodePudding user response:

You can define a base, parent Route component that wraps the Route(s) child component(s), for example:

<Routes>
  <Route path="/" element={<App />}>
    <Route index element={<Home />} />
    <Route path="carte" element={<CarteComponent />}>
      <Route path=":mapPostId/:mapPostSlug/:urlSourceId?/:urlFeatureId?/:urlFeatureAction?" element={<SingleMapPage/>} />      
    </Route>
  </Route>
</Routes>
  • Related