[React Native] 리액트 네이티브 Navigation 사용하기 (라우팅)

2022. 10. 21. 18:53·Front-End/React Native

리액트 네이티브에서 가장 많이 사용되는

라이브러리 중 하나인 React Navigation을 활용해서

하단 탭 바를 구현해 보겠습니다.

 

리액트의 라우터를 사용하는 것과 비슷합니다.

 


📝 공식 문서

 

✔ 공식 문서에 예제 코드가 나와있으니 따라 해 봅시다. 😀

https://reactnavigation.org/docs/getting-started/

 

https://reactnavigation.org/docs/getting-started/

 

reactnavigation.org

 

⦁ 설치하기

npm install @react-navigation/native
or
yarn add @react-navigation/native 

//Expo 사용 시
npx expo install react-native-screens react-native-safe-area-context

 

✔ npx expo를 사용하면 설치되어 있는 Expo와 호환되는 라이브러리 버전이 설치됩니다.

 

🤔저는 npm을 사용했더니 설치가 끝나지 않는 이슈가 발생해서 yarn을 사용하니까 해결되었습니다.
yarn을 추천드립니다.

 

⦁ 예제 코드

import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

function HomeScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home!</Text>
    </View>
  );
}

function SettingsScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Settings!</Text>
    </View>
  );
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

✔ 공식 문서의 코드입니다. 이해하기 복잡하지는 않습니다.

createBottomTabNavigator() 메서드로 내비게이터를 생성합니다.

 

이 외에도 다양한 네비게이터가 있으니 공식 문서를 찾아보는 것을 추천드립니다.

 

 

⦁ 탭 아이콘 커스터마이징

// You can import Ionicons from @expo/vector-icons/Ionicons if you use Expo or
// react-native-vector-icons/Ionicons otherwise.
import Ionicons from 'react-native-vector-icons/Ionicons';

// (...)

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;

            if (route.name === 'Home') {
              iconName = focused
                ? 'ios-information-circle'
                : 'ios-information-circle-outline';
            } else if (route.name === 'Settings') {
              iconName = focused ? 'ios-list-box' : 'ios-list';
            }

            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
          tabBarActiveTintColor: 'tomato',
          tabBarInactiveTintColor: 'gray',
        })}
      >
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

✔ <Tab.Navigator> 태그에 옵션을 줄 수 있습니다.

route.name을 if문으로 처리해서 원하는 아이콘을 return 하면 됩니다.

 

 

👍아이콘 사이트

https://icons.expo.fyi/

 

@expo/vector-icons directory

 

icons.expo.fyi

 


📝 완성 결과

 

공식 문서를 따라해서 손쉽게 예쁜 하단 탭 바를 만들었습니다. 🎉 

아이콘은 마음에 드는 것을 찾아서 넣으면 됩니다.

 

⦁ 소스코드

더보기
import * as React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Fontisto } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import { FontAwesome } from '@expo/vector-icons';

function HomeScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home!</Text>
    </View>
  );
}

function ChartScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Chart!</Text>
    </View>
  );
}

function MarketScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Market!</Text>
    </View>
  );
}

function IssueScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Issue!</Text>
    </View>
  );
}

function MyPageScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>MyPage!</Text>
    </View>
  );
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;

            if (route.name === 'Home') {
              iconName = "home"
              return <AntDesign name={iconName} size={size} color={color}/>
            } else if (route.name === 'Chart') {
              iconName = "line-chart"
            } else if (route.name === 'Market'){
              iconName = "shopping-bag-1"
            } else if (route.name === 'Issue') {
              return <FontAwesome name="newspaper-o" size={24} color="black" />
            } else {
              return <Ionicons name="person" size={size} color={color}/>;
            }

            // You can return any component that you like here!
            return <Fontisto name={iconName} size={size} color={color} />;
          },

          tabBarActiveTintColor: 'tomato',
          tabBarInactiveTintColor: 'gray',
        })}
      >
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Chart" component={ChartScreen} />
        <Tab.Screen name="Market" component={MarketScreen} />
        <Tab.Screen name="Issue" component={IssueScreen} />
        <Tab.Screen name="MyPage" component={MyPageScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

 

⦁ 페이지 이동은 어떻게 시켜요?

더보기
function HomeScreen({ navigation }) {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text>Home!</Text>
            <Button
                title="Go to Settings"
                onPress={() => navigation.navigate('Chart')}
            />
        </View>
    );
}

✔ 리액트에서 <a href="URL"> 지정해 주는 것처럼, 

스크린에 {navigation} 을 선언하고, navigation.navigate('스크린 이름')을 사용하면 됩니다. 

 

 

 


 


참고 문헌 : 

 

'Front-End > React Native' 카테고리의 다른 글

[React Native] 리액트 네이티브 링크 Linking 사용방법  (0) 2022.11.17
[React Native] 리액트 네이티브 라인 차트 만들기 (react-native-chart-kit)  (0) 2022.10.31
[React Native] 리액트 네이티브 코드 적용 안되는 이슈 해결 (캐시 초기화)  (2) 2022.10.26
[React Native] 리액트 네이티브 안드로이드 실행 방법 (Open Android)  (0) 2022.10.21
[React Native] 리액트 네이티브 To Do 앱 만들기 (AsyncStorage, Map)  (0) 2022.10.20
'Front-End/React Native' 카테고리의 다른 글
  • [React Native] 리액트 네이티브 라인 차트 만들기 (react-native-chart-kit)
  • [React Native] 리액트 네이티브 코드 적용 안되는 이슈 해결 (캐시 초기화)
  • [React Native] 리액트 네이티브 안드로이드 실행 방법 (Open Android)
  • [React Native] 리액트 네이티브 To Do 앱 만들기 (AsyncStorage, Map)
현기
현기
  • 현기
    현기의 개발블로그
    현기
  • 전체
    오늘
    어제
    • 분류 전체보기 (120)
      • Front-End (39)
        • Next (5)
        • React (8)
        • React Native (11)
        • Flutter (0)
        • Vue (1)
        • JSP (9)
        • HTML, CSS, JS (5)
      • Back-End (16)
        • Node.js (3)
        • Spring (8)
        • Flask (1)
        • AWS (4)
      • DB (5)
        • Oracle (4)
        • MySQL (1)
      • Python (7)
      • Java (27)
        • 자바 이론 (17)
        • 코딩테스트 연습 & 실습 (10)
      • 자료구조 & 알고리즘 (7)
        • 코딩테스트 (6)
        • 알고리즘 (1)
      • 블록체인 (0)
      • 프롬프트 엔지니어링 (0)
      • CS 지식 (5)
      • IT뉴스 (0)
      • 일상 (3)
      • etc (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    react-native-chart-kit
    서블릿
    포스트맨
    node.js
    파이썬
    React Native Chart
    IS-A
    Python
    스택
    react
    Spring
    JDBC
    오블완
    오라클
    큐
    그리디
    React Native
    next-intl
    자바스크립트
    상속
    리액트 네이티브
    자바
    Java
    쓰레드
    Express
    REST API
    자바 스프링
    JSP
    티스토리챌린지
    DI
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
현기
[React Native] 리액트 네이티브 Navigation 사용하기 (라우팅)
상단으로

티스토리툴바