React Native Override Android Hardware Back Button Behavior

Hardware back button is a most important part of every android mobile phone. Back button gives us the functionality to going back in previous activity without any customization in application. If we would on the main home page activity screen then by default pressing back button would exit us from the app. In react native we can modify the android’s hardware back button behavior and override it according to our requirement. We can also disable android’s hardware back button. So in this tutorial we would learn about Override Android Hardware Back Button Behavior in react native.

What we are doing in this tutorial:

In this tutorial we would override the current hardware back button behavior and show a Alert dialog message asking user to leave the application. If user press the Yes button then we would use the
BackHandler.exitApp() inbuilt function to exit manually from application and if user press the No button then it will simply print a message in console.

Contents in this project React Native Override Android Hardware Back Button Behavior:

1. Import StyleSheet, Platform, View, Text, Alert and BackHandler component in App.js file.

2. Create constructor() in your project. Here we would bind the back_Button_Press() function with current this object of class.

3. Create componentWillMount() function and adding event listener with BackHandler component. Using this we would define our function here which we would call on back button press.

4. Create componentWillUnmount() function and again remove event listener with BackHandler component. It will remove the event listener on back button press event.

5. Creating back_Button_Press() main function. In this function we would create a Alert dialog message with YES and NO button. On YES button press event we would call the default BackHandler.exitApp() function. This function allow us the exit from the app. At last we would return true in function to enable back button override behavior.

6. Create a simply text component in render’s return block.

7. Creating Style.

8. Complete source code for App.js file class.

Screenshots:


Override Android Hardware Back Button Behavior