반응형
React 프로젝트를 진행할 때 제가 자주 사용하는 방법 중 하나 입니다. react-router-dom 이 v6 로 넘어오며 이 방법을 사용하고 있지는 않지만, ReactNative 할 때 react-navigator 를 사용할 때 이용하는 방법 입니다.
우선, 결론
//App.tsx
<NavigatorContainer>
<Tab.Navigator>
{
rootRouter.map((item, key) =>
return <Tab.Screen
name={item.name}
component={item.component}
options={{headerShown : false}}
/>
)
}
</Tab.Navigator>
</NavigatorContainer>
//RootRouter.ts
import { ComponentType } from 'react';
interface RouterInterface {
name : string;
component : ComponentType<any>;
}
export RootRouter:RouterInterface[] = [
{
name='Home',
component = HomeComponent
},
{
name='Map',
component = MapsComponent
},
{
name='Setting',
component = SettingComponent
},
]
내가 생각한 문제점
//App.tsx
<NavigatorContainer>
<Tab.Navigator>
<Tab.Screen name={'Home'} component={HomeComponent} options={{headerShown : false}}/>
<Tab.Screen name={'Map'} component={MapsComponent} options={{headerShown : false}}/>
<Tab.Screen name={'Setting'} component={SettingComponent} options={{headerShown : false}}/>
</Tab.Navigator>
</NavigatorContainer>
기존에는 이러한 방식으로 라우팅을 하였는데 이게 많아질수록 App.tsx 파일의 내용물이 좀 지저분해 질 것 같다는 생각이 들었습니다.
또, 공통적인 옵션인 headerShown 옵션이 있어 같은 항목이 반복됩니다.
이렇게 된다면 코드가 길어질 뿐 아니라, 반복되는 부분도 생겨 이 부분을 어떻게 해야 조금 더 편하게 관리하고 코드가 지저분해지지 않을까? 라는 생각을 가지게 되었습니다.
getApiData.map((item, key) => return <ItemCard data={item} /> )
그러다 문득 api 를 호출할 때 Array.map() 을 이용해 반복되는 컴포넌트를 배치햇던 기억이 뇌리를 스쳤습니다.
이 원리를 이용한다면, 조금 더 깔끔하게 관리할 수 있을것 같다는 생각이 들었습니다.
//RootRouter.ts
import { ComponentType } from 'react';
interface RouterInterface {
name : string;
component : ComponentType<any>;
}
export RootRouter:RouterInterface[] = [
{
name='Home',
component = HomeComponent
},
{
name='Map',
component = MapsComponent
},
{
name='Setting',
component = SettingComponent
},
]
우선 이런식으로 배열을 만들어주고, 그 안에 값들을 json 형태로 만들어 주었습니다.
//App.tsx
<NavigatorContainer>
<Tab.Navigator>
{
rootRouter.map((item, key) =>
return <Tab.Screen
name={item.name}
component={item.component}
options={{headerShown : false}}
/>
)
}
</Tab.Navigator>
</NavigatorContainer>
이 후 map 함수를 이용해 컴포넌트 별로 속성값을 넣어주고, 공통되는 options 는 추가적으로 넣어 주었습니다.
이렇게 한다면, 앞으로 라우터를 추가할땐 RootRouter.ts 파일 안에 새로운 json Object만 추가해주면 됩니다.
반응형
'JavaScript > ReactJS' 카테고리의 다른 글
[ReactJS] react-router-dom V6 바뀐 라우팅 (0) | 2022.01.07 |
---|---|
[ReactNative] 카카오 로그인 구현하기 -1 (2) | 2021.12.23 |
[ReactJS] 상태관리 라이브러리 Redux / store 와 connect()() (0) | 2021.05.29 |
[ReactJS] 리액트 경고 : Assign object to a variable before exporting as module default (1) | 2021.05.27 |
[ReactJS] 상태관리 라이브러리 Redux / 설치와 적용법 (0) | 2021.05.25 |