androidreactjsreact-nativereact-navigationreact-navigation-stack

BackHandler in React Native isn't working


const RootNav = createStackNavigator(
  {
    Splash: {
        screen:Splash
    },
    BeforeLogin: {
        screen:BeforeLogin
    },    
    Signin: {
        screen:Signin,
    },
    Signup: {
        screen:Signup
    },
    Tabs: {
        screen:TabHolder,
    },
    ForgotPassword: {
        screen:ForgotPassword
    },
  } );

Below is the BackHandler I used in my BeforeLogin screen.

  componentWillMount() { 
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); 
  } 
  
  componentWillUnmount() { 
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); 
  }

  handleBackButton = () => { 
    BackHandler.exitApp(); 
  }

Below is the BackHandler I have used in my Signin screen and Signup screen.

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress',() => {   
 
      this.props.navigation.navigate('BeforeLogin');
      return true;

    });
  } 

My BeforeLogin screen has 2 buttons. Signin and Signup which navigates me to Signin and Signup screen.

Now, there are 2 scenarios which I'm facing.

Scenario 1: I am on BeforeLogin screen and I don't navigate to either Signin or Signup screen. And now, when I press my android back buttton, it closes the app. And that's what I want, to be able to close the app when user presses back button from BeforeLogin screen.

Scenario 2: I am on BeforeLogin screen and I navigate to either Signin or Signup screen. And now when I go back to BeforeLogin screen and then press android back button, the app isn't closing now.

How can I solve my Scenario 2?


Solution

  • Don't use backhander unnecessarily because it wan't run on ios devices.

    Either navigate using this.props.navigation.replace("")

    i.e. if you navigate from A to B and don't want to go back to A when back button is pressed simply don't use this.props.navigation.navigate("B") instead use this.props.navigation.replace("B")

    or

    try react-navigation@3.0's new fetaure SwitchNavigator.

    In this by default app will close for all route screen used in switch navigator when back button is pressed. So define all screen for which you want to exit app in SwitchNavigator and everything else in StackNavigator or whatever you use.