재귀함수를 사용하여 배열로 부터 Route를 생성하자.
<BrowserRouter>는 <Route>로 정의하며 부모와 자식간의 관계로 나타냅니다.
하지만, Array등으로 정의해서 관리하지않으면 복잡하고 보기 어려운 코드로 변질됩니다.
나쁜예) App.jsx
<BrowserRouter>
<Routes>
<Route key={'/'} path={'/'} element={<HomePage />}>
{/*자식 Route 정의 */}
<Route key={'child'} path={'/child'} element={<ChildPage />} />
</Route>
<Route key={'first'} path={'/first'} element={<FirstPage />} />
<Route key={'1'} path={'/second'} element={<SecondPage />} />
<Route key={'2'} path={'/third'} element={<ThirdPage />}>
<Route key={'child'} path={'/child'} element={<ChildPage />} />
</Route>
.....
<Route key={'10'} path={'/last'} element={<LastPage />} />
</Routes>
</BrowserRouter>
그래서, Data API를 사용하는 Router는 Array로 Route 정의를 관리합니다.
좋은예) routes.js
const routes = [
{
path: '/',
element: <HomePage />,
},
{
path: '/first',
element: <FirstPage />,
},
{
path: '/second',
element: <SecondPage />,
},
{
path: '/styled',
element: <StyledPage />,
},
];
따라서 아래와 같은 방법으로 <Route>를 동적으로 생성하는 방법으로 위와 같이 Array로 관리가 가능합니다.
import routes from '@/routes';
...
const Router = () =>{
<Routes {getRoutes(routes)}</Routes>
}
...
const getRoutes = (routes) => {
return routes.map((route, index) => {
return (
<Route key={route.path || index} path={route.path} element={route.element}>
{route.children && getRoutes(route.children)}
</Route>
);
});
};
React Router Transition 효과 적용 (0) | 2023.01.20 |
---|---|
Data API를 지원하지 않는 Router Components (0) | 2023.01.20 |
React Router - Data API를 사용하는 Router (0) | 2023.01.20 |
React Router (0) | 2023.01.20 |
댓글 영역