How to exit from the app with user confirmation in react native

Why We Need :

There are lot’s of cases where you need to the app confirmation message, such as – Sometimes it happens, the user does not want to exit from the app intentionally but he exited, just because he presses back button more than one time and you didn’t put any app confirmation message resultant user exit from the app unintentionally and need to open the app again, so let’s start the “How to exit from the app with user confirmation in react native“.

https://www.itechinsiders.com/ - react native app exit
https://www.itechinsiders.com/ – react native app exit
  • We use backhandler for app exiting, backhandler handle all the process related to the app back.

Step 1:

Firstly, we need to declare the listener at the time of page load so we add it on componentDidMount –

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

Step 2:

Now we are going to provide the definition of handleBackButton function –

handleBackButton = () => {
      Alert.alert( 
      'Exit From App', 'Do you want to Exit From App?', 
      [{ text: 'Cancel', onPress: () = > console.log('Cancel'),   
      style: 'cancel' }, 
     { text: 'OK',  onPress: () = > BackHandler.exitApp() }, ],    { 
     cancelable: false } ) 
    return true; 
}   
  • Step 3: At the time when you redirect from one page to another then you need to remove listener, so we implement it on componentWillUnmount
componentWillUnmount() {  
  BackHandler.removeEventListener('hardwareBackPress', 
  this.handleBackButton);
} 

That’s it, I hope you find this post helpful.

Then you can find my post on medium as well click here please follow me on medium as well.

So the topic  “How to exit from the app with user confirmation in react native” is completed, “you can find the next issue list here.

And if any other query/issue then please comment.

Happy Coding Guyz.

Related Post