Search code examples
reactjsurlroutesparametersreact-router-dom

React-router-dom v6. How do I route child components on a page by parameters?


We need to display a PageA with one child component depending on the "documentType" parameter ("ActsTable" or "ContractsTable") using the URL: "/worker/:documentType/:workerID". Without the "*" symbol, the child components are not rendered, but even with that symbol, you can't get parameters through the "useParams" hook. How to fix routing, given that "PageA" component sends its child prosses?

Architecture

Container component:

const Container = () => {
    ...
  return (
    <div>
      ...
      <Routes>
        <Route
          path={`/worker/*`}
          element={<PageA/>}
        />
        <Route
          path={`/user`}
          element={<PageB/>}
        />
         <Route
          path={`/stock`}
          element={<PageC/>}
        />
        ...
      </Routes>
    </div>
  );
};

PageA component:

const PageA = () => {
  const {documentType, workerID} = useParams();
    ...
  return (
    <div>
      ...
      <Routes>
        <Route
          path={`acts/:workerID`}
          element={<ActsTable props1={props1} props2={props2} />}
        />
        <Route
          path={`contracts/:workerID`}
          element={<ContractsTable props3={props3} props4={props4} />}
        />
      </Routes>
    </div>
  );
};

I tried to get the parameters just by cutting the URL from the string, but it's a crutch. I would like to useParams. Right now it returns: {"*": "acts/de34556fc987vte5f11"} rather than {"documentType": "acts", "workerID": "de34556fc987vte5f11"}.


Solution

  • Container component:

    ...
    <Route
      path={`worker/*`}
      element={<PageA/>}
    >
      <Route
        path={`:documentType/:workerID`}
      />
    </Route>
    ...