2

I have created 2 components named Layout and Homepage. Then I have added Layout in return and implement 2 route inside it with Homepage component. Now am trying to get params by useParams hook inside Layout component while I am in the location of /10. Is it possible? It is giving blank in my side.

App.js

const App = () => {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<Homepage />} />
        <Route path="/:id" element={<Homepage />} />
      </Routes>
    </Layout>
  );
}

Layout.js

import { useParams } from "react-router-dom";

const Layout = () => {
  const params = useParams();
  console.log(params);
  return(
    <div>
      Hello World
    </div>
  );
}

1 Answers1

3

Issue

The Layout component is rendered outside the Routes component that manages the route matching and route params it renders.

Solution

The common pattern for rendering layouts is to render the layout component into a route and have the layout render an Outlet for its nested routes to be rendered out on.

const Layout = () => {
  const { id } = useParams();

  useEffect(() => {
    console.log({ id });
  }, []);

  return (
    <div>
      Hello World
      <Outlet /> // <-- nested routes output here
    </div>
  );
};

Routes

<Routes>
  <Route path="/" element={<Layout />}>
    <Route path=":id" element={<Homepage />} /> // <-- rendered into outlet
    <Route index element={<Homepage />} />      // <-- rendered into outlet
  </Route>
</Routes>

Edit get-params-from-outside-of-route-component-in-react-router-6

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Is there a similar solution for version 5 ? – Oleksandr Fomin Feb 04 '23 at 07:03
  • @OleksandrFomin What do you need a solution for in RRDv5? – Drew Reese Feb 04 '23 at 07:16
  • I need to access URL params from outside the route in a layout component – Oleksandr Fomin Feb 04 '23 at 07:48
  • @OleksandrFomin Would the [useRouteMatch](https://v5.reactrouter.com/web/api/Hooks/useroutematch) be helpful then? If not, then it may be for the best that you post an entirely new question on SO with supporting [mcve]. If you do this then please feel free to ping me in another comment here with a link to it and I can take a look when available. – Drew Reese Feb 04 '23 at 07:51