Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v6, nested routes with a default path for the parent [duplicate]

I did not know how to construct the proper question title, sorry for that. But in a route structure like below, I want the admin path to always show organisations as the default/index, like whenever you navigate to /admin it automatically navigates to /admin/organisations, but for instance in other path /admin/users, or /admin/organisations/create the related components renders.

is such a requirement doable with routes, createBrowserRoute?

const routes = createBrowserRouter([
  {
    path: '/',
    element: <AppShell />,
    children: [
      {
        path: 'admin',
        element: <AdminPanel />,
        children: [
          { path: 'organisations', element: <Organisations /> },
          { path: 'users', element: <Users /> }
        ]
      }
    ]
  }
]);

currently, I have a useEffect in the AdminPanel component like

React.useEffect(()=>{
    if(window.location.pathName === "/admin" ) navigate("/admin/organisations")
},[])

But is it doable via react-router props?

I have chosen this structure (children array) because all the sub-admin paths should have access to the side menu and according to react-router official tutorial it was the best approach

OBS! index element takes the route/path name of the parent, in my case I wanted the index behavior with a different path name. So it is not considered a duplicate of the flagged question, at least the accepted answer there does not answer my question, though the second answer does.

like image 681
Amir-Mousavi Avatar asked Oct 24 '25 16:10

Amir-Mousavi


1 Answers

also you can use this : Link

const router = createBrowserRouter([
  {
    path: '/',
    element: <AppShell />,
    children: [
      {
        path: 'admin',
        element: <AdminPanel />,
        children: [
          {
            index: true,
            element: <Navigate to="/admin/organisations" replace />,
            // when user navigate to /admin it automaticly navigate to /admin/organisations
          },
          { path: 'organisations', element: <Organisations /> },
          { path: 'users', element: <Users /> },
        ],
      },
    ],
  },
]);
like image 168
Abbas Bagheri Avatar answered Oct 27 '25 06:10

Abbas Bagheri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!