ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React #2 React Router 중첩경로

    Library/React 2023. 8. 15. 09:32

    HTML 구조 설계 시에 아래와 같이 header, aside, footer 는 공통으로 사용하고 section 영역의 콘텐츠만 변경하도록 하고 싶은 경우가 있다. 혹은 사이드에 메뉴바를 고정적으로 위치시키고 그 외의 공간을 콘텐츠 영역으로 사용하고자 하는 경우 thymeleaf layout 기능을 사용했었다.

    html layout

    React 에서는 이런 화면을 구성하려고 할 때 React Router의 Outlet을 활용할 수 있다. Outlet은 React Router v6에서 도입된 개념으로, 중첩된 경로를 다루는데 사용되는 기능이다.

     

    import { BrowserRouter, Route, Routes, Outlet } from 'react-router-dom';
    
    const App = () => (
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/parent" element={<Parent />}>
            <Route path="child1" element={<Child1 />} />
            <Route path="child2" element={<Child2 />} />
          </Route>
        </Routes>
      </BrowserRouter>
    );
    
    const Parent = () => (
      <div>
        <h2>Parent Component</h2>
        <Outlet /> {/* 중첩된 경로의 컴포넌트를 여기에 렌더링 */}
      </div>
    );
    
    const Child1 = () => <h3>Child 1</h3>;
    const Child2 = () => <h3>Child 2</h3>;
    const Home = () => <h2>Home Page</h2>;

     

    이와 같은 코드에선 /parent 하위의 child1, child2가 중첩 경로가 된다. 그리고 부모 컴포넌트, 즉 Parent 컴포넌트에 <Outler /> 태그를 위치시키면 자식 컴포넌트를 outlet 위치에 렌더링한다. 

     

    그렇다면 어느 정도의 깊이로 중첩이 가능할까?

    중첩된 경로의 children은 계층 구조이며 몇 단계까지든 중첩이 가능하다. 하지만 부모 - 자식 관계에서 바로 상위 부모의 Outlet 위치에 렌더링되기 때문에 중첩 구조를 유지하며 코드를 관리하기가 어렵다.

     

    아래의 예시를 보면 Child2 컴포넌트 하위에 Grandchild 컴포넌트가 위치해있으며 Child2 컴포넌트 안에 Outlet이 위치해있다. 

    1. /parent/child1: Child1 컴포넌트가 렌더링됩니다.
    2. /parent/child2: Child2 컴포넌트가 렌더링됩니다.
      • /parent/child2/grandchild: Grandchild 컴포넌트가 Child2 컴포넌트 내부에서 렌더링됩니다.
    import { BrowserRouter, Route, Routes, Link, Outlet } from 'react-router-dom';
    
    const App = () => (
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/parent" element={<Parent />}>
            <Route path="child1" element={<Child1 />} />
            <Route path="child2" element={<Child2 />}>
              <Route path="grandchild" element={<Grandchild />} />
            </Route>
          </Route>
        </Routes>
      </BrowserRouter>
    );
    
    const Home = () => <h2>Home Page</h2>;
    const Parent = () => (
      <div>
        <h2>Parent Component</h2>
        <Outlet />
      </div>
    );
    const Child1 = () => <h3>Child 1</h3>;
    const Child2 = () => (
      <div>
        <h3>Child 2</h3>
        <Outlet />
      </div>
    );
    const Grandchild = () => <p>Grandchild</p>;
    
    export default App;

    중첩 경로를 활용하면 어플리케이션의 구조를 세분화하고 컴포넌트를 분리하면서 재사용이 용이해진다. 또한 수정이 필요한 경우 각 컴포넌트에서 수정이 이루어지기 때문에 관리하기가 쉽다.

     

Designed by Tistory.