How to use BackHandler with React Navigation in React Native
On Android devices, users prefer the hardware back button to navigate back. Even though the actions of the back button are generally desirable, sometimes you may need to customize the action of the hardware button.
In this blog post, Let’s see how to customize the back button actions using BackHandler and react-navigation library. The BackHandler API of react native is used to detect when the hardware back button of an Android device is pressed.
In the following react native example I am customizing the action of the hardware back button so that the app quits. With react-navigation and BackHandler, we can subscribe to navigation life cycle updates to add a custom listener.
The following code snippet using useFocusEffect hooks from react navigation does the purpose for us.
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
Alert.alert('Hold on!', 'Are you sure you want to go back?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{text: 'YES', onPress: () => BackHandler.exitApp()},
]);
return true;
};
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
onBackPress,
);
return () => subscription.remove();
}, []),
);
Following is the complete code.
import React from 'react';
import {StyleSheet, Button, Alert, View, BackHandler} from 'react-native';
import {useFocusEffect} from '@react-navigation/native';
import {ScreenProp} from './types';
const Screen1 = ({navigation}: ScreenProp) => {
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
Alert.alert('Hold on!', 'Are you sure you want to go back?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{text: 'YES', onPress: () => BackHandler.exitApp()},
]);
return true;
};
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
onBackPress,
);
return () => subscription.remove();
}, []),
);
return (
<View style={styles.container}>
<Button
onPress={() => {
navigation.navigate('Screen2');
}}
title="Learn More"
color="#841584"
/>
</View>
);
};
export default Screen1;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2c3e50',
},
});
Following is the output.
That’s how you use backhandler with react navigation in react native.
2 Comments