1

I've defined nested routes using createBrowserRouter and I expected that the router would route to my child page. However, it seems to stop at the top-level part of the url. BlogsPage and SampleBlog are both React components.

I expected "https://adomain/blogs/sampleblog" to get routed to SampleBlog not to BlogsPage. I thought I could nest as deeply as I liked and that the router would match the longest matching path and invoke that component.

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    errorElement: <ErrorPage />,
    children: [
      { path: "", element: <HomePage /> },
      { path: "home", element: <HomePage /> },
      {
        path: "blogs",
        element: <BlogsPage /> },
        children: [
          { path: "sampleblog", element: <SampleBlog /> },
        ]
      },
    ]
  },
]);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Steve Buck
  • 56
  • 4

1 Answers1

1

children are used to render child-routes. You would need to use an <Outlet /> inside BlogsPage

What you wanted to do is creating two routes at the same level

[
  { path: "blogs", element: <BlogsPage /> },
  { path: "blogs/sampleblog", element: <SampleBlog /> }
]
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • If I have to define a child at the same nested level as parent, when do you use a nested route? Intuitively it seemed that what I did was what I would have expected to do. – Steve Buck Nov 07 '22 at 16:19
  • It's not a child. You use a child when you want to render the parent as well. – Konrad Nov 07 '22 at 16:23
  • 1
    To clarify this, a child is used when the parent is a "container" (rendered as well) and the parent has an component in its output where the child is to be rendered. – Steve Buck Nov 07 '22 at 16:45