Nested Routes(중첩 라우트)를 작성하는 방법엔 두 가지가 있다.
자식 Route를 가지는 부모 Route의 path 뒤에 다른 경로가 더 붙는다는 뜻으로 /*
(와일드카드)를 붙여줘서 해당 Route 내부에서 또다른 Route가 렌더 될 수 있음을 명시한다.
Router.tsx
<BrowserRouter>
<Routes>
<Route path="/:coinId/*" element={<Coin />} />
<Route path="/" element={<Coins />} />
</Routes>
</BrowserRouter>
부모 Route가 렌더링하는 컴포넌트(위의 경우 <Coin/>
)에서 자식 Route들의 path와 element를 작성해준다.
Coin.tsx
<Routes>
<Route path="chart" element={<Chart />} />
<Route path="price" element={<Price />} />
</Routes>
상대경로를 지원하기 때문에 path="/:coinId/price"
로 작성할 필요없이 path="chart"
로 작성해도 정상 동작한다.
Router.tsx에서 자식 Route들을 부모 Route로 감싸준다.
Router.tsx
<BrowserRouter>
<Routes>
<Route path="/" element={<Coins />} />
<Route path="/:coinId/*" element={<Coin />}>
<Route path="chart" element={<Chart />} />
<Route path="price" element={<Price />} />
</Route>
</Routes>
</BrowserRouter>
부모 Route가 렌더링 하는 컴포넌트(Coin.tsx
) 안에서 자식 Route들이 어디에 렌더 될 지 <Outlet />
으로 표시한다.
Coin.tsx
<Container>
<Overview />
<Outlet />
</Container>