React-router-dom 중첩 라우터(nested routes)

드엔트론프·2023년 1월 24일
0

중첩 라우터는 말 그대로 중첩되게 라우터를 쓰는 것이다.
기본적으로는 react-router-dom은 BrowserRouter - Routes - Route를 같은 레벨에 작성한다.

	<BrowserRouter>
      <Routes>
          <Route path=":movieId" element={<DetailPage />} />
          <Route path="search" element={<SearchPage />} />
      </Routes>
	</BrowserRouter>

중첩 라우팅을 쓴다 하면 다음과 같이 작성할 수 있다.

      <Routes>
        <Route path="/test" element={<Layout />}>
          <Route index element={<MainPage />} />
          <Route path=":movieId" element={<DetailPage />} />
          <Route path="search" element={<SearchPage />} />
        </Route>
      </Routes>

설명

크게 Layoutelement로 하는 Route가 나머지 Route를 감싸고 있다.

  • react의 children을 쓰는 것과 매우 유사하다!
    부모 컴포넌트 내부에서 자식 컴포넌트 정보에 접근할 때 쓰는 prop이 children이다.

  • Layout 에는 headerfooter가 있다. 그리고 <Outlet /> 이 있다.

const Layout = () => {
  return (
    <div>
      <Nav />
      <Outlet />
      <Footer />
    </div>
  );
};
  • Layout 안에 <Outlet /> 이 바로 react의 children 같은 느낌으로 이해하면 좋다.

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered.
<Outlet>은 하위 경로 요소를 렌더링하기 위해 상위 경로 요소에서 사용해야 합니다. 이렇게 하면 하위 경로가 렌더링될 때 중첩된 UI가 표시될 수 있습니다.

  • 예시에서 <Outlet /><MainPage /> <DetailPage /> <SearchPage /> 이 친구들을 의미한다.

굳이 중첩 라우터를 쓰는 이유는 무엇일까?
위의 예시로 살펴보자면, localhost:3000/test로 갔을 때
localhost:3000/test 가 메인 페이지가 되고 (index element가 메인의 역할을 해준다.)
localhost:3000/test/search 로 가면 검색페이지로 갈 수 있다.

중첩으로 작성하지 않았다면
localhost:3000/search?q=ba로 갔을 것이다.

임의로 test를 넣었지만 사실 test 빼면 /search로 바로 가긴한다

profile
왜? 를 깊게 고민하고 해결하는 사람이 되고 싶은 개발자

0개의 댓글