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>
);
}
Layout component needs to render its children so the routes are actually rendered. I tried this though and it didn't seem to pick up on the route params. Sorry, it isn't immediately clear as to why at this point.
The common pattern for rendering layouts is to render the layout component into a route and have the layout render an Outlet for its children/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>