Home >Web Front-end >JS Tutorial >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
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> </> ); };
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; };
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} />; };
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!