Ionic React "hardware backbutton" closes modal but navigates back to root of app

Viewed 321

I am trying to close a modal with the native Android back button in my project. The below code closes the modal but navigates back to the root of the project.

 document.addEventListener('backbutton', (event) => {
            if(modalIsOpen === true) {
                setIsOpen(false);
                event.preventDefault();
            } 
            else if(modalIsOpen === false && history.location.pathname === "/tabs/home"){
           App.exitApp();
            }
        });

My other solution was to use the capacitor App plugin

const ionRouter = useIonRouter();
     document.addEventListener('ionBackButton', (ev) => {
         ev.detail.register(-1, () => {
             if (modalIsOpen === true) {
                 setIsOpen(false);
                 event.preventDefault();
             }
             else if (modalIsOpen === false && !ionRouter.canGoBack()) {
                 App.exitApp();
             }
         });
     });

Neither work the way I desired them to work and really would love to figure this out! I also tried use history.push(); to push to the page the modal was close on to stop the navigation back to the root which worked but not for all pages.

Any help would be greatly appreciated.

1 Answers

There could be other event listeners for the backbutton event. You might try using event capturing:

addEventListener('backbutton', () => { … }, { capture: true });

I’d also recommend moving the event.preventDefault() to the start of your callback.

Related