Home > Web Front-end > JS Tutorial > How to Render Different Layouts in React Router v6?

How to Render Different Layouts in React Router v6?

Susan Sarandon
Release: 2024-12-25 13:43:09
Original
736 people have browsed it

How to Render Different Layouts in React Router v6?

Rendering Components with Different Layouts/Elements Using React Router v6

In React Router v6, rendering components with different layouts or elements can be achieved using nested routes or a routes configuration with the useRoutes hook.

Nested Routes

To render the and components on all routes except the login route, create a layout component that renders them and an outlet for nested routes.

const AppLayout = () => (
  <>
    <NavBar />
    <SideBar />
    <main className={styles["main--container"]}>
      <div className={styles["main--content"]}>
        <Outlet />
      </div>
    </main>
  </>
);

const App = () => {
  return (
    <>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route element={<AppLayout />}>
          <Route path="/" element={<Dashboard />} />
        </Route>
      </Routes>
    </>
  );
};
Copy after login

Routes Configuration and useRoutes Hook

Alternatively, use a routes configuration and the useRoutes hook to define your routes:

const routesConfig = [
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    element: <AppLayout />,
    children: [
      {
        path: "/",
        element: <Dashboard />,
      },
    ],
  },
];

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

const App = () => {
  const routes = useRoutes(routesConfig);

  return routes;
};
Copy after login

Routes Configuration and Data Routers (v6.4.0 Only)

As of React Router v6.4.0, you can also use data routers to define your routes:

const routesConfig = [
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    element: <AppLayout />,
    children: [
      {
        path: "/",
        element: <Dashboard />,
      },
    ],
  },
];

import { createBrowserRouter, RouterProvider } from 'react-router-dom';

const router = createBrowserRouter(routesConfig);

const App = () => {
  return <RouterProvider router={router} />;
};
Copy after login

The above is the detailed content of How to Render Different Layouts in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template