안녕하세요
React Outlet: 이중 라우트 구현하기 본문
React Router Outlet 예시
<Router>
<Routes>
<Route />
<Route />
<Route />
<Route
path="/user"
element={
<ParentComponent>
<Outlet />
</ParentComponent>
}
>
<Route path={'profile1'} element={<ChildComponent1 />} />;
<Route path={'profile2'} element={<ChildComponent2 />} />;
<Route path={'profile3'} element={<ChildComponent3 />} />;
</Route>
</Routes>
</Router>
Outlet을 사용하여 중첩된 라우트를 작성할 수 있습니다.
path="/all" 대신에 path="all"로 작성해야 합니다.
위의 코드 예시에서는 /user/profile1, /user/profile2, /user/profile3 이 route 됩니다.
- <Router>: 앱 전체를 감싸고 있는 라우터입니다.
- <Routes>: 실제 라우팅 규칙을 정의하는 컴포넌트입니다.
- <Route>: 하나의 경로와 해당 경로에 해당하는 컴포넌트를 매핑하는 라우터 컴포넌트입니다.
- <Outlet>: 자식 <Route> 컴포넌트들을 렌더링하는 컴포넌트입니다.
이 컴포넌트를 사용하면 자식 <Route> 컴포넌트를 중첩해서 사용할 수 있습니다.
<ParentComponent>
<Outlet />
</ParentComponent>
=> ParentComponent 컴포넌트로 Outlet 을 감싼 형태입니다.
<Route path={'profile1'} element={<ChildComponent1 />} />;
=> /user/profile1 경로로 Oulter 컴포넌트에는 자식 Route의 element인 <ChildComponent1 />가 props로 전달됩니다.
const ParentComponent = ({children}: {children: React.ReactNode}) => {
return (
<div>
{children}
</div>
);
};
위와 같이 ParentComponent의 props로 children인 <ChildComponent1 />을 받아옵니다.
이 때 type은 {children: React.ReactNode} 로 지정하면 됩니다.