69 lines
1.5 KiB
Markdown
69 lines
1.5 KiB
Markdown
# Layouts in React Router
|
|
|
|
## 📌 What is a Layout?
|
|
A **layout** in React Router is just a **React component** that wraps multiple pages with shared structure or styling (e.g., header, footer, sidebar).
|
|
|
|
Layouts usually contain:
|
|
- Global UI elements (navigation, footer, etc.)
|
|
- An `<Outlet />` component where nested routes will render their content
|
|
|
|
---
|
|
|
|
## 📂 Folder Structure Example
|
|
|
|
src/
|
|
layouts/
|
|
├── MainLayout.jsx
|
|
└── AdminLayout.jsx
|
|
pages/
|
|
├── HomePage.jsx
|
|
├── AboutPage.jsx
|
|
└── DashboardPage.jsx
|
|
|
|
|
|
---
|
|
|
|
## 🛠 How Layouts Are Used in Routes
|
|
|
|
### 1. Layout as a Parent Route
|
|
Use the layout component as the `element` of a **parent route** and place **pages** inside as nested routes.
|
|
|
|
```jsx
|
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
|
import MainLayout from "./layouts/MainLayout";
|
|
import HomePage from "./pages/HomePage";
|
|
import AboutPage from "./pages/AboutPage";
|
|
|
|
function App() {
|
|
return (
|
|
<BrowserRouter>
|
|
<Routes>
|
|
<Route element={<MainLayout />}>
|
|
<Route path="/" element={<HomePage />} />
|
|
<Route path="/about" element={<AboutPage />} />
|
|
</Route>
|
|
</Routes>
|
|
</BrowserRouter>
|
|
);
|
|
}
|
|
|
|
export default App;
|
|
```
|
|
|
|
### 2. Inside the MainLayout.jsx
|
|
|
|
```jsx
|
|
import { Outlet } from "react-router-dom";
|
|
|
|
export default function MainLayout() {
|
|
return (
|
|
<>
|
|
<header>Header</header>
|
|
<main>
|
|
<Outlet />
|
|
</main>
|
|
<footer>Footer</footer>
|
|
</>
|
|
);
|
|
}
|
|
``` |