• 5
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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.

Scenaraio 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 Scenaraio 2: ? Please help.

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.

  • 1
Reply Report
    • I used this.props.navigation.replace('BeforeLogin'); instead of this.props.navigation.navigate('BeforeLogin'); in Signin and Signup Screen and now my BackHandler in BeforeLogin screen works! Thank you :)