Skip to content
Advertisement

Navigate through child routes using react-router-dom V6

I am using react-router-dom V6 both Routes and useRoute, So, in the site, the main routes are as follow:

export default function App() {
  return (

    <Routes>
      <Route path="/" element={<Components />} />
      <Route path="admin" element={<AdminApp />} />
    </Routes>


  )
}

As see above the second Route’s element is <AdminApp /> this element is coming from the following:

export default function AdminApp() {
  return useRoutes([
    {
      path: '/dashboard',
      element: <DashboardLayout />,
      children: [
        { path: '/', element: <Navigate to="/dashboard/app" replace /> },
        { path: 'app', element: <DashboardApp /> },
        { path: 'user', element: <User /> },
        { path: 'products', element: <Products /> },
        { path: 'blog', element: <Blog /> }
      ]
    },
    {
      path: '/',
      element: <LogoOnlyLayout />,
      children: [
        { path: 'login', element: <Login /> },
        { path: 'register', element: <Register /> },
        { path: '404', element: <NotFound /> },
        { path: '/', element: <Navigate to="/dashboard" /> },
        { path: '*', element: <Navigate to="/404" /> }
      ]
    },

    { path: '*', element: <Navigate to="/404" replace /> }
  ]);
}

So whenever i call the route /admin nothing display in the screen and in the console log I am getting this warning

index.tsx:90 You rendered descendant <Routes> (or called `useRoutes`) at "/admin" (under <Route path="admin">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

Please change the parent <Route path="admin"> to <Route path="admin/*">

I have changed <Route path="admin" element={<AdminApp />} /> to <Route path="admin/*" element={<AdminApp />} /> so the warning disappeared but the page displays blank when i navigate to the route admin/ and it replace admin word with dashboard in the url:

what happened:

http://localhost:3000/admin => http://localhost:3000/dashboard

what expected:

http://localhost:3000/admin => http://localhost:3000/dashboard/app

Advertisement

Answer

I have replaced ‘/’ in first child route to ” and it worked for me. something like this :

return useRoutes([
    {
      path: "dashboard",
      children: [
        { path: "", element: <Navigate to="dashboard/app" replace /> },
        { path: "app", element: <DashboardApp /> },
        { path: "user", element: <User /> }
      ]
    }
  ]);

Here is simple app working example

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement