728x90
728x90

뒤로가기 기능 막는 방법

들어가며

  • 리액트 네이티브(React Native)를 이용하여 만든 앱에서 특정 스크린에서 뒤로가기 기능을 막는 방법을 간단하게 정리해본다.

 

방법

방법 ① : BackHandler API 이용하기 (Android)

  • @react-native@ 패키지의 @BackHandler@ API를 사용해서 뒤로가기 이벤트를 무시하도록 설정할 수 있다.
  • 이 방법은 안드로이드(Android)에서 물리적인 뒤로가기 기능을 막아준다.
    • iOS에서는 물리적인 뒤로가기 버튼이 없기 때문에 별도로 처리해주지 않아도 된다.
import { useEffect } from 'react';
import { BackHandler } from 'react-native';

function myApp() {
  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      () => true   // true를 반환하면 뒤로가기를 막는다.
    );

    return () => backHandler.remove();   // 컴포넌트 언마운트 시 이벤트를 제거한다.
  }, []);

  return (
    // ...
  );
}

 

화면이 언마운트될 때 @backHandler.remove()@로 반드시 이벤트 해제 처리를 해준다. (이벤트 해제를 하지 않으면 메모리 누수 이슈가 발생한다.)

 

 

방법 ② : useNavigation의 beforeRemove 이벤트 활용하기 (Android, iOS)

  • iOS에서 뒤로가기를 막기 위해선 @navigation options@와 @beforeRemove@ 이벤트를 활용해야 한다.
import { useEffect } from 'react';
import { Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function CameraOnLiveVideoCallScreen() {
  const navigation = useNavigation();

  useEffect(() => {
    const unsubscribe = navigation.addListener('beforeRemove', (e) => {
      // 뒤로가기 동작 막기
      e.preventDefault();

      // 사용자 확인 등 원하는 로직
      Alert.alert('나가기', '영상통화를 종료하시겠습니까?', [
        { text: '취소', style: 'cancel', onPress: () => {} },
        { text: '확인', onPress: () => navigation.dispatch(e.data.action) },
      ]);
    });

    return unsubscribe;
  }, [navigation]);

  return (
    // ...
  );
}

 

  • 또한 해당 스크린의 Stack 설정 시, @getstureEnabled: false@를 추가해준다.
<Stack.Screen
  name="CameraOnLiveVideoCall"
  component={CameraOnLiveVideoCallScreen}
  options={{
    gestureEnabled: false, // iOS 스와이프 제스처 막기
    headerShown: false,    // 필요 시 헤더 숨기기
  }}
/>

 

 

위의 방법을 사용하면 안드로이드와 iOS 모두에서 뒤로가기 기능을 막을 수 있다.

 

정리

플랫폼 BackHandler API 동작 여부 대안
Android O @BackHandler.addEventListener@
iOS X @navigation.addListener('beforeRemove', ...)@

 

참고 사이트

 

BackHandler · React Native

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.

reactnative.dev

 

Preventing going back | React Navigation

Sometimes you may want to prevent the user from leaving a screen to avoid losing unsaved changes. There are a couple of things you may want to do in this case:

reactnavigation.org

 

728x90
728x90