Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App exit on back click on android in react native?

on Android Mi Note 3, hardware back button is not fire the handleBackPress , when I will click on back the app exit.

I have do the following code but the handleBackPress is not called.

 componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
  }

  handleBackPress = () => {
    this.goBack(); // works best when the goBack is async
    return true;
  }

Navigation Code :

const ModalSignUp = createStackNavigator(
  {
    Signup: { screen: Signup, key: 'Signup' },
    PartyList: { screen: PartyList, key: 'PartyList' },
    StatesList: { screen: StatesList, key: 'StatesList' },

  },
  {
    initialRouteName: 'Signup',
    headerMode: 'none',
    mode: 'card',
  }
);

Navigate :

this.props.navigation.push("StatesList")

Expected :

back click on hardware button, go to previous screen.

like image 249
Kirit Modi Avatar asked Jun 29 '26 12:06

Kirit Modi


1 Answers

Your error can be in the way you get the next view of react-navigation.

You need to use .push to create a new view on the stack and when you click the back button, the .goBack() will be triggered.

By default, back button will always make the navigation to go back on the stack, but if you have only one view in the stack (this happens when you only use .navigate) the app will exit.

Not sure how you are navigating through the views, but this can be a solution.

Edit: To solve this problem, when navigating through views, use navigation.push('viewname') instead of navigation.navigate('viewname'). You don't need any other method (like the one you put in the question).

Also check the docs to understand the how navigating works or this question

like image 77
Vencovsky Avatar answered Jul 02 '26 07:07

Vencovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!