简体   繁体   中英

react router v6 and nest UI and URL

I am trying to figure out what this bit of code means:

<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route
      path="messages"
      element={<DashboardMessages />}
    />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>

https://reactrouter.com/docs/en/v6/components/route

If the location is / , then the rendered UI will be

<Dashboard />

While if the location is /messages , then the rendered UI will be

<Dashboard >
  <DashboardMessages />
<Dashboard />

Same logic for /tasks and /about .

Is my understanding correct?

Your understanding is partly correct. Given the following routing code:

<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route path="messages" element={<DashboardMessages />} />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>

It is correct that when the URL path is "/" that only the Dashboard component is rendered. This is what is called a Layout Route . Layout routes generally provide some common component lifecycle and/or common UI layout, ie headers and footers, navbars, sidebars, etc.

When the URL path is "/messages" or "/tasks" the Dashboard component is rendered as well as the specifically matched routed content DashboardMessages or DashboardTasks into an Outlet component rendered by Dashboard .

Note that the "/about" route is outside the "/" dashboard layout route. When the path is "/about" then only AboutPage is rendered.

Here's an example layout route components:

import { Outlet } from 'react-router-dom';

const AppLayout = () => {
  ... common logic ...

  return (
    <>
      <Header />
      <Outlet /> // <-- nested routes render element here
      <Footer />
    </>
  );
};

const NavbarLayout = () => (
  <>
    <Navbar />
    <Outlet /> // <-- nested routes render element here
  </>
);

...

<Routes>
  <Route element={<AppLayout />}>
    ... routes w/ header/footer & w/o navbar

    <Route element={<NavbarLayout />}>
      ... routes also w/ navbar
    </Route>

    ...
  </Route>

  ... routes w/o header/footer
</Routes>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM