[React Native] React Navigation

suno·2023년 1월 3일
post-thumbnail

What is?

React Native에서 다른 페이지를 이동할 수 있게 해주는 라이브러리.


Why use?

웹 브라우저에서는 anchor <a> 태그로 페이지를 이동한다. 페이지를 클릭하면 URL이 히스토리 스택에 추가되고, 뒤로가기 버튼을 누르면 스택의 마지막 아이템을 꺼내서 이전 페이지로 이동한다.

하지만 React Native에는 글로벌 히스토리 스택이라는 개념이 내장되어 있지 않아서 React Navigation이 히스토리 역할을 도와준다.

웹 브라우저의 네비게이션과 다른 점은, React Navigation은 안드로이드, ios에서 사용하는 제스쳐와 애니메이션을 지원한다.


Getting Started

expo project의 경우

# 기본 설치
yarn add @react-navigation/native
npx expo install react-native-screens react-native-safe-area-context
# native stack
npm install @react-navigation/native-stack

Examples

// In App.js in a new project

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();
// Stack object를 반환함. { Screen, Navigator }로 구성됨.

function App() {
  return (
		// NavigationContainer로 감싸야 함.
		<NavigationContainer>
      <Stack.Navigator initialRouteName='Home'>
        <Stack.Screen name='Home' component={Home} />
        <Stack.Screen name='Profile' component={Profile} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

페이지 이동하기

컴포넌트에서 navigation props를 받아와서, navigation.navigate(스택 이름)으로 이동한다.

function Home({ navigation }) {
  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <Button
        title='Go to Profile'
				// 다른 페이지로 이동
        onPress={() => navigation.navigate('Profile')}
      />
      <StatusBar style='auto' />
    </View>
  );
}

같은 페이지로 이동하기

navigate() 메소드를 사용하면 동일한 페이지로는 여러번 이동하지 않고 무시된다.

보통 params를 사용할 때 같은 컴포넌트로 이동해야 할 경우가 있는데, 이때는 push() 메소드를 사용한다.

function Profile({ navigation }) {
  return (
    <View style={styles.container}>
      <Text>Profile</Text>
      <Button
        title='Go to Profile again'
        // 같은 페이지로 이동
        onPress={() => navigation.push('Profile')}
      />
      <Button 
        title='Go back' 
				// 뒤로가기
        onPress={() => navigation.goBack()} />
      <StatusBar style='auto' />
    </View>
  );
}

뒤로가기

Go Back

기본적으로 페이지를 이동하면 Native Stack Navigator 헤더에 뒤로가기 버튼이 자동으로 생성된다.

만약 동적으로 뒤로가기를 하려면 goBack() 메소드를 사용한다.

Home으로 이동하기

  • navigation.navigate(’Home’)
  • navigation.popToTop()

Route 초기화하기

reset() 메소드를 사용하여 현재 route 히스토리와 상관 없이 stack을 임의로 초기화할 수 있다.

아래 코드는 routes 배열로 히스토리를 초기화하고, index가 1인 Profile 페이지로 이동한다는 의미이다.

navigation.reset({
  index: 1,
  routes: [{ name: 'Home' }, { name: 'Profile' }],
});

타이틀 지정하기

setOptions() 메소드로 route name 대신 임의의 타이틀을 지정할 수 있다.

아래 코드는 결과적으로 동일하게 title을 변경한다.

// Stack Router에서 options 전달
<Stack.Screen
  name='Home'
  component={Home}
  options={{ title: 'Overview' }}
/>

// 컴포넌트에서 동적으로 options 할당
function Home({ navigation }) {
  useEffect(() => {
    navigation.setOptions({
      title: 'Overview',
    });
  }, [navigation]);

  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <Button
        title='Go to Profile'
        onPress={() => navigation.navigate('Profile')}
			/>
      <StatusBar style='auto' />
    </View>
  );
}

Stack.Navigator Props

initialRouteName

초기에 보여줄 페이지를 지정한다.

ScreenOptions

  • title: 타이틀
  • headerBackTitle: 뒤로가기 버튼 타이틀
  • presentation: 스크린을 이동하는 방식 (card, modal 등 다양한 스타일 존재)
  • animation: 페이지 이동 시 애니메이션

How to Use Params

Params 전달하기

navigate() 메소드의 두번째 인자로 params 객체를 전달한다.

function Home({ navigation }) {
  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <Button
        title='Go to Profile'
        onPress={() =>
          navigation.navigate('Profile', {
            userId: 1,
            name: 'Hyojin',
          })
        }
      />
      <StatusBar style='auto' />
    </View>
  );
}

Params 받기

route props의 params 객체를 이용한다.

function Profile({ navigation, route }) {
  const { userId, name } = route.params;

  return (
    <View style={styles.container}>
      <Text>Profile</Text>
      <Text>UserId: {userId}</Text>
      <Text>Name: {name}</Text>
      <Button
        title='Go to Profile again'
        onPress={() => navigation.push('Profile')}
      />
      <Button title='Go back' onPress={() => navigation.goBack()} />
      <StatusBar style='auto' />
    </View>
  );
}

Reference

profile
Software Engineer 🍊

0개의 댓글