How to close React Native App using BackHandler API
Device back button handling
When you want your app to be able to exit using the back handler, the react native BackHandler api is used to make this happen. Here is two example codes, one for class based component and one for fictional based component.
For class based component Here is the code
import { BackHandler } from 'react-native';
constructor() {
super();
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
BackHandler.exitApp();
return true;
}
For functional based component here is a good example
import { BackHandler } from 'react-native';
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
return () => {
BackHandler.removeEventListener(
"hardwareBackPress",
handleBackButtonClick
);
};
}, []);