Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router dom 6 route structure with layouts

I have this page structure

  • login (Root page)
  • forget password
  • dashboard (Wrapper layout needed)
  • orders (Wrapper layout needed)

The orders page and Dashboard needed the wrapper layout.

Right now I have this code

const routes = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<RootLayout />}>
      <Route path="orders" element={<Orders />} />
      <Route path="dashboard" element={<Dashboard />} />
    </Route>
  )
);

And this is root layout

export default function RootLayout() {
  return (
    <div>
      <header>
        <h1>This top header</h1>
      </header>
       
      <main>
        <Outlet/>
      </main>
    </div>
  )
}

I am unsure how I can add Login page to the root path and Forget password page to the "/forget-password" path. RootLayout should not wrap in those two pages as well.

I have tried this approach even though it is adding a extra "/app" part. But this also not working as intended

createRoutesFromElements(
  <Route path="/" element={<Login  />}>
    <Route path="app" element={<RootLayout />}>
      <Route path="orders" element={<Orders />} />
      <Route path="dashboard" element={<Dashboard />} />
    </Route>
  </Route>
)

How can I achieve this with react-router-dom@6?

like image 545
Pathum Kalhan Avatar asked Oct 22 '25 13:10

Pathum Kalhan


1 Answers

createRoutesFromElements expects a single React node. Render a single "outer" route on "/" with no element which will render an Outlet by default. "RootLayout" is a layout route and doesn't need to participate in the route path matching, omit the path="app" prop.

createRoutesFromElements(
  <Route path="/">
    <Route index element={<Login />} /> // <-- "/"
    <Route
      path="forgot-password             // <-- "/forgot-password"
      element={<ForgotPassword />}
    />

    <Route element={<RootLayout />}>
      <Route
        path="orders"                   // <-- "/orders"
        element={<Orders />}
      />
      <Route
        path="dashboard"                // <-- "/dashboard"
        element={<Dashboard />}
      />
    </Route>
  </Route>
)
like image 61
Drew Reese Avatar answered Oct 24 '25 03:10

Drew Reese



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!