Search code examples
reactjsreact-router-dom

Children route not loading the component


I am trying to create a router configuration using createBrowserRouter. Something like below:

export const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: '/',
        element: <Home />,
      },
      {
        path: '/templates',
        element: (
            <Templates />
        ),
        children: [
          {
            path: 'template-history/:templateId', // Define template-history and templateId as parameters
            element: <Reports />,
          },
        ],
      },
    ],
  },
  
]);

 



I need to create children to template. Like the URL will be "http:localhost:3000/template/template-history/123".

issue is If I try the above url its redirecting to http:localhost:3000/


Solution

  • The issue after Outlet is rendered is "localhost:3000/templates/template-histoty/1" this url is loading both templates and templates history component in the UI together.

    This is how layout routes work with the Outlet and their nested routes. If you want Templates and Reports to render independently you'll need to make them sibling routes.

    Examples:

    export const router = createBrowserRouter([
      {
        element: <Root />,
        errorElement: <ErrorPage />,
        children: [
          { path: '/', element: <Home /> },
          {
            path: 'templates',
            children: [
              {
                index: true,
                element: <Templates />,
              },
              {
                path: 'template-history/:templateId',
                element: <Reports />,
              },
            ],
          },
        ],
      },
    ]);
    
    export const router = createBrowserRouter([
      {
        path: '/',
        element: <Root />,
        errorElement: <ErrorPage />,
        children: [
          { path: '/', element: <Home /> },
          {
            path: 'templates',
            element: <Templates />,
          },
          {
            path: 'templates/template-history/:templateId',
            element: <Reports />,
          },
        ],
      },
    ]);