React Native Expo Navigation 설정하기 (+TypeScript)

2023. 12. 7. 17:55·Development Study/Mobile
728x90

들어가며

React Native Expo를 통해 프로젝트를 생성했다면, 이제 각각의 화면마다 이를 넘겨주는 기능이 필요하다. 이에 TypeScript와 함께 사용하는 방법을 보도록 하겠다.

React에 React Router DOM이 있듯이 React Native에는 react-navigation이 있다.
이 글에서는 프로젝트를 생성한 상태에서 "home", 그리고 "login"을 만들어 두 페이지끼리 이동하도록 해볼 것이다.


1. Install Packages

먼저 네비게이션과 관련되어있는 모듈들을 설치한다.

# 이 부분은 이상하게 npx expo를 통해 설치하면 오류가 발생한다.
yarn add @react-navigation/stack
# 나머지 패키지 설치(expo cli 사용)
npx expo install react-native-screens react-native-safe-area-context

2. Set Navigation: App.tsx

주로 Native 프로젝트를 생성하면 처음에 "App.tsx" 라는 파일을 볼 수 있을 것이다.
이 파일에 네비게이션을 세팅해두겠다.

먼저, 필요한 모듈들을 "import"해온다.

// App.tsx
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import React from "react";
import LoginPage from "./screens/login";
import Home from "./screens/home";
import { RootStackParamList } from "./types/navigationTypes";


이후 "Stack"을 선언해 네비게이션 사용을 위한 스택을 생성해준다.

// App.tsx
const Stack = createNativeStackNavigator<RootStackParamList>();
// RootStackParamList는 Navigation에 들어가는 스크린에 대한 파라미터로, App.tsx 함수 이후 보여줄 예정


이제 메인 함수에 네비게이션 세팅을 해둔다.

// App.tsx
export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name='Login' component={LoginPage} />
        <Stack.Screen name='Home' component={Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}


여기서 중요한 점은 <Stack.Navigator> 안에 있는 페이지가 서로 영향을 받는다는 것이다.
만약 앱을 켰을 때 "Home" 페이지를 먼저 띄우게 하고 싶다면 두 순서를 변경하면 된다.

// App.tsx
<Stack.Screen name='Home' component={Home} />
<Stack.Screen name='Login' component={LoginPage} />


"RootStackParamList"는 위에서 지정해둔 스택들에 대한 타입으로, 한 화면에서 다른 화면으로 넘어가기 위해 미리 설정해두는 타입니다.
타입의 내용들은 아래와 같이 구성되어있다.

// types/navigationTypes.ts
export type RootStackParamList = {
  Home: undefined;
  Login: undefined;
};

3. Set Navigation: Login.tsx & Home.tsx

이제부터 위에 구성된 "Home", 그리고 "LoginPage"에서 아주 간단하게 버튼을 통해 스크린을 이동시켜볼 것이다.

그럼 아래와 같이 "Login.tsx"와 "Home.tsx"를 작성해보자.

// /screens/login.tsx
import React from "react";
import { View, Text, Button } from "react-native";
import { StackNavigationProp } from "@react-navigation/stack";
import { RootStackParamList } from "../types/navigationTypes";

// 네비게이션 prop 타입 정의
type LoginScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  "Login"
>;

type LoginProps = {
  navigation: LoginScreenNavigationProp;
};

const LoginPage: React.FC<LoginProps> = ({ navigation }) => {
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Login Page</Text>
      <Button title='Go to Home' onPress={() => navigation.navigate("Home")} />
    </View>
  );
};

export default LoginPage;
// /screens/home.tsx
import React from "react";
import { View, Text, Button } from "react-native";
import { StackNavigationProp } from "@react-navigation/stack";
import { RootStackParamList } from "../types/navigationTypes";

type HomeScreenNavigationProp = StackNavigationProp<RootStackParamList, "Home">;

type HomeProps = {
  navigation: HomeScreenNavigationProp;
};

const Home: React.FC<HomeProps> = ({ navigation }) => {
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Home Page</Text>
      <Button
        title='Go to Login'
        onPress={() => navigation.navigate("Login")}
      />
    </View>
  );
};

export default Home;


모두 멋지게 작성하고 나면 이제 실제로 돌아가는 지 확인해 볼 차례이다.
아래의 커맨드를 통해 실행시키고 확인해보자.

npx expo start

4. Result

그럼 이제 모두 멋진 네비게이션 기능을 만들어보자!


End

728x90
저작자표시 비영리 변경금지 (새창열림)

'Development Study > Mobile' 카테고리의 다른 글

[Kotlin] Android App 개발, 그리고 Kotlin  (0) 2023.05.03
[iOS] Swift란 무엇일까?  (0) 2023.05.03
'Development Study/Mobile' 카테고리의 다른 글
  • [Kotlin] Android App 개발, 그리고 Kotlin
  • [iOS] Swift란 무엇일까?
ThreeLight
ThreeLight
ThreeLight Studio의 블로그, TimeMap.exe에 오신 것을 환영합니다.
  • ThreeLight
    TimeMap.exe
    ThreeLight
  • 전체
    오늘
    어제
    • 분류 전체보기 (245)
      • Checkpoint (1)
      • (3D)Dev Deep Dive (0)
        • Templates & Guides (9)
        • Frontend origin (9)
        • Backend origin (1)
        • TroubleShootings (4)
      • Development Study (95)
        • Frontend (36)
        • Backend (21)
        • CS(Computer Science) (2)
        • Background Knowledges (11)
        • Algorithm (2)
        • Mobile (3)
        • AWS (6)
        • Python (6)
        • MSW(MapleStoryWorlds) (8)
      • Coding Test (59)
        • 문제.zip (1)
        • BaekJoon_JavaScript (0)
        • Programmers_JavaScript (9)
        • BaekJoon_Python (23)
        • Programmers_Python (10)
        • Undefined_Python (3)
        • Programmers_SQL (13)
      • 활동내역.zip (43)
        • 개인 (21)
        • Techeer (12)
        • Bootcamp (7)
        • Hackathon (1)
        • TeamProjects (2)
      • 여기 괜찮네??(사이트 | App) (5)
      • 재미있는 주제들 (8)
      • 개발 외 공부 저장소 (11)
        • 생산운영관리 (3)
        • 생활속의금융 (6)
        • 경영정보시스템 (2)
  • 링크

    • TimeMap.dmg (Portfolio)
    • GitHub 바로가기
    • 오픈프로필(카카오톡)
    • Medium 바로가기
    • Disquiet 바로가기
    • LinkedIn 바로가기
  • 인기 글

  • 태그

    TypeScript
    programmers
    프로그래머스
    HTML
    SQL
    CSS
    Python
    Baek Joon
    react
    JavaScript
  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
ThreeLight
React Native Expo Navigation 설정하기 (+TypeScript)
상단으로

티스토리툴바