Ionic React: Close modal / alert on back button pressed

My question is how to close modal or alert when the user clicks back button on their mobile device or browser?

How to do it in Component or Functional Component?

One way would be to call the dismiss method on the modal when listening for the backButton event.

import { Plugins, Capacitor } from '@capacitor/core';
import { useEffect } from 'react';
...

const App: React.FC = () => {

  useEffect(() => {
    if (Capacitor.isNative) {
      Plugins.App.addListener('backButton', e => {
        if (currentModal !== null) {
          currentModal.dismiss();
        }
      })
    }
  }, []);

...
1 Like

I found that there is 2 ways of doing this:

The first way is what @yanisl suggested. But in my case I cannot use it because I have to handle every back button pressed, even if the back button pressed when typing inside input box.

The second way is that everytime I open my modal, I push to useHistory() (for example: I push ?modalOpened=true), then I create useEffect() to watch useLocation() whether the location contains modalOpened=true or not. If not, then close modal, if yes do nothing.

const [modalOpened, setModalOpened] = useState(false);
const location = useLocation();
const nav = useHistory();

useEffect(() => {
    if(!location.search.includes('modalOpened=true')) {
        setModalOpened(false);
    }
},[location]);

const openModal = () => {
    nav.push(nav.location.pathname + '?modalOpened=true');
    setModalOpened(true);
}

This should be made as default behaviour of modal btw.

1 Like