기존 Layout을 전체적용하고싶을 때에는 Router을 Layout컴포넌트로 감싸주었다.
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Home from '../pages/Home';
import About from '../pages/About';
import Contact from '../pages/Contact';
import Works from '../pages/Works';
import Layout from './Layout';
const Router = () => {
return (
<BrowserRouter>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="works" element={<Works />} />
</Routes>
</Layout>
</BrowserRouter>
);
};
export default Router;
하지만 나는 어떤페이지에 속한 페이지들에만 특정 layout을 적용시키고싶다.
이럴땐 react-router-dom의 Outlet을 사용하면 된다.
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import Works from "../pages/Works";
import DashBoardLayout from "./DashBoardLayout";
import MyPage from "../pages/MyPage";
import Test from "../pages/Test";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/works/:id" element={<Works />} />
<Route path="/dashboard" element={<DashBoardLayout />}>
<Route path="mypage" element={<MyPage />} />
<Route path="test" element={<Test />} />
</Route>
</Routes>
</BrowserRouter>
);
};
export default Router;
이렇게 공통적으로 적용시킬 dashboard를 self-closing하지않고 두 Route를 감싸준다.
import React from "react";
import { Outlet } from "react-router-dom";
const DashBoardLayout = () => {
return (
<div>
<h1>대쉬보드</h1>
<Outlet />
</div>
);
};
export default DashBoardLayout;
그리고 DashBoardLayout컴포넌트에서 Outlet을 import해와 사용한다.
같은 dashboardLayout이 적용된 것을 볼 수있다.
'2차 공부 > TIL' 카테고리의 다른 글
24.08.19 CRA/Vite없이 리액트 프로젝트 생성하기 (0) | 2024.08.19 |
---|---|
24.08.16 React에서 Supabase 사용하기 (0) | 2024.08.16 |
24.08.16 react-router-Dom 설정 (0) | 2024.08.16 |
24.08.16 redux 설정하기 (0) | 2024.08.15 |
24.08.16 리액트 숙련주차 강의 (3) | 2024.08.15 |