중첩 라우터는 말 그대로 중첩되게 라우터를 쓰는 것이다.
기본적으로는 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>
크게 Layout을 element로 하는 Route가 나머지 Route를 감싸고 있다.
react의 children을 쓰는 것과 매우 유사하다!
부모 컴포넌트 내부에서 자식 컴포넌트 정보에 접근할 때 쓰는 prop이 children이다.
Layout 에는 header 와 footer가 있다. 그리고 <Outlet /> 이 있다.
const Layout = () => {
return (
<div>
<Nav />
<Outlet />
<Footer />
</div>
);
};
<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로 바로 가긴한다