프로젝트를 진행하다 보면, 간단한 관리자 페이지를 자주 만들게 된다.
관리자 페이지의 특성상 비슷한 레이아웃이 반복되서 사용되기 마련이다.
간단히 그려보면
const Layout = ()=> {
return (
<div>
<Header />
<main>
<aside />
<article> { children} </article>
</main>
</div>
)
}
이런 식의 레이아웃이 있다고 했을 때, 각각의 페이지 컴포넌트에서 이 레이아웃 컴포넌트를 가져다가 사용한다면
const UserPage = ()=> <Layout> <children /> </Layout>
const StorePage = ()=> <Layout> <children /> </Layout>
const InitPage = ()=> <Layout> <children /> </Layout>
이렇게 각 페이지마다 레이아웃 컴포넌트를 선언해줘야 할 것이다. 하지만 react-router를 사용한다면, 조금 더 이쁘게 사용할 수 있다.
const Router = ()=> {
return (
<Routes element={<Layout />}>
<Route path="/" element={<InitPage />} />
<Route path="/user" element={<UserPage />} />
<Route path="/store" element={<StorePage />} />
</Routes>
)
}
// 이떄 layout컴포넌트
const Layout = () => {
return (
<div>
<Header />
<main>
<Outlet />
</main>
</div>
)
}
layout컴포넌트를 위와 같이 선언하면, 우리가 children props로 들어오는 컴포넌트를 사용하는 것 처럼 <Outlet /> 컴포넌트에서 랜더링 된다. 이렇게 좀 더 깔끔한 코드를 작성할 수 있다.