Issue
I wonder if there is a better way of hiding/not rendering parent content in react router object. I could solve it by conditional rendering, but I am not sure it is the best approach. I have parent, child and grandchild and I will render only grandchild content, but keep the nested structure(for useMatches and other things). I tried with Outlet
but it didn't help. How can I hide parent and child from DOM?
const router: RouteObject = {
id: "parent",
path: "parent",
element: <div><p>Parent</p></div>,
children: [
{
id: "child",
path: "/parent/child",
element: <div><p>Child</p></div>,
children: [
{
id: "grandchildLayout",
index: true,
element: <div><Outlet /></div>,
},
{
id: "grandchild",
path: "/parent/child/grandchild",
element: <div><p>Grandchild</p></div>,
},
],
},
],
};
Solution
Render Parent
and Child
as index routes so that they are only rendered on "/parent"
and "/parent/child"
exactly each. The parent route of each will render an Outlet
by default, or you can render a layout route component and Outlet
of your own if you do actually have some shared UI between the routes.
Example:
const router: RouteObject = {
id: "parent",
path: "parent",
children: [
{
index: true,
element: <div><p>Parent</p></div>
},
{
id: "child",
path: "/parent/child",
children: [
{
index: true,
element: <div><p>Child</p></div>
},
{
id: "grandchildLayout",
element: (
<div>
<h3>Grandchild Layout</h3>
<Outlet />
</div>
),
children: [
{
id: "grandchild",
path: "/parent/child/grandchild",
element: <div><p>Grandchild</p></div>
}
]
}
]
}
]
};
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.