React - Handle Hardware Back Button

Is it possible to handle the hardware back button in a react app?

I have seen some examples for angular apps but none for react.

I am not sure about React exactly, but I know in Angular we use HostListener with the document:backbutton event like this:

  @HostListener('document:backbutton', ['$event'])
  public backButtonHandler($event) {
    // Do back button stuff here.

Thanks for the Angular example, as for React its looks like you have to integrate directly with Capacitor.

1 Like

I also tried to handle the Android Hardware Back Button with React using the Capacitor event, however this information wasn’t true in my testing:

Listening for this event will disable the default back button behaviour

The default back button behaviour was still present and the code in my callback was executed properly.
I also found no way to remove the event as the removeListener method is private in the App class.

Just to share what I have found. There is an extra parameter you have to turn off if you want to prevent the default behavior of going back the history.

	swipeBackEnabled: false,// also prevent swiping back on either platform
	hardwareBackButton: false// this is what you need (android only)