Nested Routes

Cheddaryeon·2023년 8월 2일

1. 반복되는 레이아웃은 하나로 묶어 공통으로 사용할 수 있다

  • header
  • footer

2. 반복되는 부분을 위해 Layout이라는 컴포넌트를 만든다

  • common 폴더를 만들고 그 안에 Layout.jsx라는 파일을 만든다
    (아무데나 만들어도 되지만 폴더 구조로 어떤 파일들이 있는지 쉽게 찾을 수 있다)
  • Main.jsx에 있는 header와 footer를 복사해서 Layout 컴포넌트에 잘 붙여넣는다
     import React from "react";
     import { Outlet } from "react-router-dom";
     
     export default function Layout() {
       return (
         <div
           style={{
             minHeight: "100vh",
             position: "relative",
             paddingBottom: "90px",
             boxSizing: "border-box",
           }}
         >
           {/* Header */}
           <header
             style={{
               display: "flex",
               justifyContent: "space-between",
               padding: "24px",
               backgroundColor: "#000000",
               color: "white",
             }}
           >
             <div>로고</div>
             <div
               style={{
                 display: "flex",
                 gap: "12px",
               }}
             >
               <div>로그인</div>
               <div>회원가입</div>
             </div>
           </header>
     
           {/* footer */}
           <footer
             style={{
               marginTop: "24px",
               display: "flex",
               justifyContent: "space-between",
               padding: "24px",
               backgroundColor: "#EEEEEE",
               color: "black",
               // 아래 css 추가
               position: "absolute",
               bottom: 0,
               width: "100%",
               boxSizing: "border-box",
             }}
           >
             <div>문의하기</div>
             <div>SNS 채널들</div>
           </footer>
         </div>
       );
     }
  • App.js의 다른 Route들을 하나로 감싸는 Route를 만들고, element에 Layout을 넣는다
     function App() {
       return (
         <Routes>
     			{/* 여기 추가 */}
           <Route element={<Layout />}>
             <Route path="/" element={<Main />} />
             <Route path="/products" element={<Products />} />
             <Route path="/products/:id" element={<Product />} />
           </Route>
         </Routes>
       );
     }
  • 이제 다른 페이지에서 header, footer는 모두 지워도 좋다
  • 페이지를 열면 Layout 이외에 아무것도 안보이는 것이 당연하다
    다른 컴포넌트들을 어디에 넣을지 정하지 않았기 때문!

3. Outlet 컴포넌트 넣기

  • nested routes (안에 있는 놈들)이 어디에 보여질지 지정하는 용도로 사용한다
  • 넣고 싶은 곳에 Outlet 컴포넌트를 넣어준다
profile
study frontend

0개의 댓글