skip to Main Content

I have two sets of routes defined in different files. I want them both to be appended to the same path. There is no overlap in the route names. e.g.

const EditRoutes = () => <Routes>
  <Route path=":id/edit" element={<EditPage />} />
</Routes>

const PreviewRoutes = () => <Routes>
  <Route path=":id/preview" element={<PreviewPage />} />
</Routes>

const AppRoutes = () => <Routes>
  <Route path="/page/*">
    <PreviewRoutes />
    <EditRoutes />
  </Route>
</Routes> // Is invalid - how do I merge the two?

Following some hints from the errors, I have tried a few combinations, for example using React fragments rather than <Routes> in the child route sets but no luck.

How can I combine the routes under one path stem?

2

Answers


  1. I do apologize for not quite understanding your problem… So I’ll just post one way of fixing the error you are having and give you the results of doing such. Please leave a comment if you were expecting something else. Thanks

    const EditRoutes = () => <Routes>
      <Route path=":id/edit" element={<EditPage />} />
    </Routes>
    
    const PreviewRoutes = () => <Routes>
      <Route path=":id/preview" element={<PreviewPage />} />
    </Routes>
    
    const AppRoutes = () => <Routes>
      <Route path="/page/*" element={(<>
        <PreviewRoutes />
        <EditRoutes />
      </>)} />
    </Routes>
    

    Please be advised that the PreviewRoutes will correspond to /page/:id/preview
    And the EditRoutes will correspond to /page/:id/edit

    By using a react fragment <></> to contain both as one element you can continue to use the element prop and avoid the error you are getting.
    If this was what you wanted then I’m happy to help, if it was not what you were looking for, please explain further. Thanks

    Login or Signup to reply.
  2. You can use the component to nest the two routes together.

    const AppRoutes = () => <Routes>
      <Route path="/page/*">
        <Routes>
          <Route path=":id/edit" element={<EditPage />} />
          <Route path=":id/preview" element={<PreviewPage />} />
        </Routes>
      </Route>
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search