Reputation: 89
<Route path="/menu" element={<Menu />}>
<Route path="featured" element={<Featured />} />
<Route path="previous" element={<Previous />} />
<Route path="favourites" element={<Favourites />} />
<Route path=":categoryId/:menuId" element={<MenuDetail />} />
</Route>
<Route path="/menu" element={<Menu />} />
<Route path="/menu/featured" element={<Featured />} />
<Route path="/menu/previous" element={<Previous />} />
<Route path="/menu/favourites" element={<Favourites />} />
<Route path="/menu/:categoryId/:menuId" element={<MenuDetail />} />
I thought these two codes do the same thing but found out they do not. First one being the nested routes under menu route, and the second is just regular routes. Apparently the second code is what I want it to do.
The first one, when I go to
"/menu/featured"
"/menu/previous"
"/menu/favourites"
"/menu/:categoryId/:menuId"
They all give me Menu
component, which I do not want. So I had to try the second code to achieve what I wanted.
But aren't they the same?
If I were to achieve what I want using the nested routes, how should I write this code?
Upvotes: 1
Views: 724
Reputation: 202721
The first example the Menu
component is rendered as a layout route. Layout routes components should also render an Outlet
component for their nested routes to also render out their element
content. If only Menu
is being rendered then I suspect you are missing the Outlet
.
That said, if you wanted to make the two snippets the same then you'd render Menu
as an index route of a layout route rendered on "/menu"
. When a layout Route
is not passed an element
prop it renders just an Outlet
by default.
Example:
<Route path="/menu">
<Route index element={<Menu />} />
<Route path="featured" element={<Featured />} />
<Route path="previous" element={<Previous />} />
<Route path="favourites" element={<Favourites />} />
<Route path=":categoryId/:menuId" element={<MenuDetail />} />
</Route>
Which is equivalent to rendering them all individually unnested with fully qualified route paths.
<Route path="/menu" element={<Menu />} />
<Route path="/menu/featured" element={<Featured />} />
<Route path="/menu/previous" element={<Previous />} />
<Route path="/menu/favourites" element={<Favourites />} />
<Route path="/menu/:categoryId/:menuId" element={<MenuDetail />} />
Upvotes: 1