react-native-navigationwix-react-native-navigationreact-native-navigation-v2

How do I disable the device back button on Android (react-native)?


How can I disable the physical device back button on Android with React-Native? I don't want to enable it for the user.


Solution

  • Current open screen is tracked with a listener created when the application is launched, in app.js. Main component of the app creates a BackHandler listener, which responds to the device back button according to the currently open screen.

    Main component:

    componentDidMount() {
      BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
    }
    
    componentWillUnmount() {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
    }
    
    onBackPress = () => {
      if (this.props.currentScreen.name === 'app.main') {
         Alert.alert(
           'Confirm exit',
           'Do you want to exit App?',
           [
             {text: 'CANCEL', style: 'cancel'},
             {text: 'OK', onPress: () => {
               BackHandler.exitApp()
              }
            }
           ]
        );
      } else {
        Navigation.pop(this.props.currentScreen.id);
      }
    
      return true;
    }
    

    App.js

    //register to compomentDidApperaListener to keep track on which screen is currently open. The componentName and Id are stored in my redux store
    Navigation.events().registerComponentDidAppearListener(({ componentId, componentName }) => {
      store.dispatch(updateCurrentScreen({'name': componentName, 'id': componentId}))
    })