React Router v6 empowers you to render components with different layouts and elements. Let's tackle the specific challenge you're facing: excluding the navigation bar (NavBar) and sidebar (SideBar) from a specific route, namely the login page (LoginPage).
By default, React Router renders routes within the same layout, including components such as NavBar and SideBar. To override this behavior, introduce a separate layout component that encompasses the desired elements and provides an outlet for nested routes.
Create a layout component, AppLayout, which encapsulates NavBar and SideBar.
import { Outlet } from 'react-router-dom'; const AppLayout = () => ( <> <NavBar /> <SideBar /> <main className={styles["main--container"]}> <div className={styles["main--content"]}> <Outlet /> {/* Outlet for nested routes */} </div> </main> </> );
Modify your App component to use this layout:
const App = () => { return ( <> <Routes> <Route path="/login" element={<LoginPage />} /> <Route element={<AppLayout />}> <Route path="/" element={<Dashboard />} /> {/* Nested route */} </Route> </Routes> </> ); };
This approach renders LoginPage without NavBar and SideBar and includes them for the Dashboard route nested within AppLayout.
An alternative method is to define a routes configuration object and utilize the useRoutes hook. Here's how:
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; };
This approach dynamically renders the routes based on the routes configuration.
With React Router v6.4.0, you can employ data routers to achieve the same result:
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} />; };
This approach involves creating a createBrowserRouter instance and using RouterProvider to render the routes.
The above is the detailed content of How to Exclude NavBar and SideBar from Specific Routes in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!