Android Back Button
When the user presses the Android hardware back button in React Native, react-navigation will pop a screen or exit the app if there are no screens to pop. This is the sensible default behavior, but there are situations when you might want to implement custom handling. This is where handling the android back button is useful. You can also check react-navigation-backhandler library to handle the back press.
Event Listener for Back Button Press
To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress
event listener with a callback function, which will be called after pressing the Back Button. We should also remove the listener when we are jumping out from the screen (where we have added the listener) because sometimes after going to the next screen or any other screen the listener remains active in the background if the last screen is in the stack and not killed by the system.
The event subscriptions are called in reverse order (i.e. last registered subscription first), and if one subscription returns true then subscriptions registered earlier will not be called.
Add hardwareBackPress Event Listener
// BackHandler.addEventListener(
// <Event Name>,
// <Function to be Called>
//);
BackHandler.addEventListener('hardwareBackPress', onBackPress);
Remove hardwareBackPress Event Listener
// BackHandler.removeEventListener(
// <Event Name>,
// <Function>
//);
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
Handle the event
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
// Do Whatever you want to do on back button click
// Return true to stop default back navigaton
// Return false to keep default back navigaton
return true;
};
BackHandler.addEventListener(
'hardwareBackPress', onBackPress
);
return () =>
BackHandler.removeEventListener(
'hardwareBackPress', onBackPress
);
}, [])
);
Returning true from onBackPress
denotes that we have handled the event, and react-navigation’s listener will not get called, thus not popping the screen. Returning false will cause the event to bubble up and react-navigation’s listener will pop the screen.
What we are going to do?
In our example, we are going from FirstPage to SecondPage using navigate and after clicking Back Button on SecondPage we will navigate to ThirdPage with an alert. So let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependencies
To install the dependencies open the terminal and jump into your project
cd ProjectName
1. Install react-navigation
npm install @react-navigation/native --save
2. Other supporting libraries react-native-screens
and react-native-safe-area-context
npm install react-native-screens react-native-safe-area-context --save
react-native-screens
package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java
file which is located in android/app/src/main/java/<your package name>/MainActivity.java
.
Add the following code to the body of MainActivity
class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
and make sure to add the following import statement at the top of this file below your package statement:
import android.os.Bundle;
This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.
3. For the Stack Navigator install
npm install @react-navigation/native-stack --save
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Project File Structure
To start with this Example you need to create a directory named pages in your project and create three files FirstPge.js, SecondPage.js, and ThirdPage.js.
Code to Handle Android Back Button
Now Open App.js in any code editor and replace the code with the following code
App.js
// Handling Android Back Button Press in React Native
// https://aboutreact.com/handling-android-back-button-press/
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
import ThirdPage from './pages/ThirdPage';
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FirstPage">
<Stack.Screen
name="FirstPage"
component={FirstPage}
options={{
title: 'First Page', //Set Header Title
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
<Stack.Screen
name="SecondPage"
component={SecondPage}
options={{
title: 'Second Page', //Set Header Title
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
<Stack.Screen
name="ThirdPage"
component={ThirdPage}
options={{
title: 'Third Page', //Set Header Title
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Open pages/FirstPage.js in any code editor and replace the code with the following code.
FirstPage.js
// Handling Android Back Button Press in React Native
// https://aboutreact.com/handling-android-back-button-press/
import React from 'react';
import {Button, View, Text, SafeAreaView} from 'react-native';
const FirstPage = ({navigation}) => {
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is the First Page of the app
</Text>
<Button
onPress={
() => navigation.navigate('SecondPage')
}
title="Go to Second Page"
/>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
Handling Android Back Button
{'\n'}
React Navigation
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default FirstPage;
Open pages/SecondPage.js in any code editor and replace the code with the following code.
SecondPage.js
// Handling Android Back Button Press in React Native
// https://aboutreact.com/handling-android-back-button-press/
import React from 'react';
import {
Button,
View,
Text,
SafeAreaView,
BackHandler
} from 'react-native';
import {
useFocusEffect
} from '@react-navigation/native';
const SecondPage = ({navigation}) => {
// useFocusEffect get called each time when screen comes in focus
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
navigation.navigate('ThirdPage');
// Return true to stop default back navigaton
// Return false to keep default back navigaton
return true;
};
// Add Event Listener for hardwareBackPress
BackHandler.addEventListener(
'hardwareBackPress',
onBackPress
);
return () => {
// Once the Screen gets blur Remove Event Listener
BackHandler.removeEventListener(
'hardwareBackPress',
onBackPress
);
};
}, []),
);
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is Second Page of the App
</Text>
<Text
style={{
textAlign: 'center',
marginBottom: 16,
}}>
Use "Go back" Button to go to First Screen
else use back button of your Android device
to go to Third Screen
</Text>
<Button
title="Go back"
onPress={() => navigation.goBack()}
/>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
Handling Android Back Button
{'\n'}
React Navigation
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default SecondPage;
Open pages/ThirdPage.js in any code editor and replace the code with the following code.
ThirdPage.js
// Handling Android Back Button Press in React Native
// https://aboutreact.com/handling-android-back-button-press/
import React from 'react';
import {
View,
Text,
SafeAreaView,
BackHandler
} from 'react-native';
import {
useFocusEffect
} from '@react-navigation/native';
const ThirdPage = () => {
// useFocusEffect get called each time when screen comes in focus
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
alert('Back Press handled and doing no action');
// Return true to stop default back navigaton
// Return false to keep default back navigaton
return true;
};
// Add Event Listener for hardwareBackPress
BackHandler.addEventListener(
'hardwareBackPress',
onBackPress
);
return () => {
// Once the Screen gets blur Remove Event Listener
BackHandler.removeEventListener(
'hardwareBackPress',
onBackPress
);
};
}, []),
);
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is Third Page of the App
</Text>
<Text
style={{
textAlign: 'center',
marginBottom: 16,
}}>
In this screen with the help of BackHandler
we are overriding the default back navigation
and generating Alert (For Android)
</Text>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
Handling Android Back Button{'\n'}React Navigation
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default ThirdPage;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
That was the way to handle the Android Back Button. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
you can set condition for costume function that u write for hardware button , for example when ( for example for React Native Router Flux ) Actions.currentScene === ‘Home’ do something or other conditions u want .
Yes. We can.
hii Snehal Agrawal aboutreact.com website is very important for beginner for react native developer.
I m react native developer. I have two years experience in react native. I want ask please make tutorial on react native axios library on timeout funtionality. actually in case internet not reachable in device react native axios show the possible handle network request failed.
hi, Snehal Agrawal This is a very good site to give a beginner developer – like me – a chance to learn to react-native from scratch and give us code examples with explanations…I love this content and I hope you continue to enhance our code