I'm using Ionic with React to develop an app. I could't find any documentation about how to handle hardware back button click and how to exit from app. Is any docs or tutorials about that?
Asked
Active
Viewed 4,833 times
3
-
Have a look here https://forum.ionicframework.com/t/hardware-back-button-with-ionic-4/137905/6 – Azzam Asghar Jan 29 '20 at 06:36
-
@AzzamAsghar there are decisions just for angular – Азизджон Дадабоев Jan 29 '20 at 07:27
-
You are right i am not sure but i guess `platform` service is not available in react as it is in `angular`. Have a look here accepted answer has some interesting workarounds perhaps you make them work for you https://stackoverflow.com/questions/51728175/ionic-4-alternative-for-platform-registerbackbuttonaction – Azzam Asghar Jan 29 '20 at 07:46
-
@AzzamAsghar Thanks, I find answers in Capasitor docs – Азизджон Дадабоев Jan 29 '20 at 08:54
3 Answers
7
Import These Inside the App.tsx File
import React, { useEffect } from "react";
import { Plugins, Capacitor } from "@capacitor/core";
Create an effect for handling back button
useEffect(() => {
if (Capacitor.isNative) {
Plugins.App.addListener("backButton", (e) => {
if (window.location.pathname === "/") {
// Show A Confirm Box For User to exit app or not
let ans = window.confirm("Are you sure");
if (ans) {
Plugins.App.exitApp();
}
} else if (window.location.pathname === "/YourFirstPageRoute") {
// Show A Confirm Box For User to exit app or not
let ans = window.confirm("Are you sure");
if (ans) {
Plugins.App.exitApp();
}
}
});
}
}, []);

Ashirbad Panigrahi
- 634
- 6
- 13
-
should I also setupConfig({ hardwareBackButton: false }) ? Nothing happened when I did so – fifth Dec 02 '20 at 02:53
1
To exit app after click back button on hardware, first you have to prevent default history back. https://ionicframework.com/docs/react/config
// App component
import { setupConfig } from '@ionic/react'
setupConfig({
hardwareBackButton: false
})
then add Listener back-button
https://capacitor.ionicframework.com/docs/apis/app#method-addListener-3
import { Plugins, Capacitor } from '@capacitor/core'
...
useEffect(() => {
if (Capacitor.isNative) {
Plugins.App.addListener('backButton', e => {
// Use of location.pathname is also correct
if (window.location.pathname === '/') {
Plugins.App.exitApp()
} else if (window.location.pathname === '/detail') {
history.push('/')
} else {
history.back()
}
})
}
}, []) // eslint-disable-line
...
-
2Wont this stop the back button from closing other views like a modal? – Dev Yego Oct 17 '20 at 05:23
-
@DevYego you are correct. Above code can't deal with other views like a modal. I can't find any solution in react ionic document. So I think that we need to save other view's open state with store like mobx, redux, etc. Then, back button be pressed, other view have to be closed. – junho Oct 17 '20 at 08:14
0
Well, you can make confirm alert before the exit on your main/home/dashboard page. I have added IonAlert with 2 buttons. Please have a look at my working code in actual device below:
import React, {useState } from 'react';
import { IonAlert } from '@ionic/react';
import { Plugins } from "@capacitor/core";
const HomePage: React.FC = () => {
const { App } = Plugins;
const [showBackAlert, setShowBackAlert] = useState(false);
// listening to ionic back button event
document.addEventListener('ionBackButton', (ev: any) => {
ev.detail.register(-1, () => {
// when you are in your home(last) page
if (history.location.pathname === '/home') {
// calling alert box
setShowBackAlert(true);
}
});
});
return (
<IonPage>
<IonAlert
isOpen={showBackAlert}
header={'Please Confirm!'}
message={'Do you really want to exit our App?'}
buttons={[
{
text: 'Nope',
role: 'cancel',
cssClass: 'secondary',
handler: () => {}
},
{
text: 'Yeah',
handler: () => {
App.exitApp();
}
}
]}
onDidDismiss={() => setShowBackAlert(false)}
cssClass='my-custom-class'
/>
</IonPage >
);
};
export default HomePage;

Kapil Raghuwanshi
- 867
- 1
- 13
- 22
-
I'm interested in how you will debug that `console.log` when running on a device. This method doesn't work for me, I've tried using the native toasts to see if this listener is ever called but nothing. – Dev Yego Oct 19 '20 at 16:27
-
No, those console logs are just for chrome testing purposes. Let me remove those now, but this method is perfectly working on my app. Download and check (https://play.google.com/store/apps/details?id=com.kialabs.bingesearch). – Kapil Raghuwanshi Oct 21 '20 at 07:30