Ion sheet modal persists after you leave the page

Hi, so I have a page on my app where there is an Ion sheet modal that can expand and collapse to a min value, while maintaining interaction with the background (example here).
Since I have backdropDismiss={false} and isOpen={true}
the modal does not go away when you interact with the page, and it is always visible on the page.

BUT, it also doesn’t go away when I route to an entirely different page. I can get around this by setting isOpen={false} when the navigation buttons are clicked, but can someone help me understand why the IonModal doesn’t get taken out of the DOM when an entirely new IonPage is rendered?

To clarify, If I have an open sheet modal on Main.tsx, and I get routed to Profile.tsx, the modal stays open on Profile.tsx when it ideally should be contained to Main.tsx.

I also cannot say ion-modal { display: none !important; } on a page’s css, because it has a global scope and hides it on the main page too.

A workaround I have found is the following css rules:

ion-modal {
  display: none !important;
}
.ion-page ~ ion-modal {
  display: flex !important;
}

this works because the modal when displayed on the main page initially is in this structure:

<IonApp>
    <IonPage name='mainPage'></IonPage>
    <IonModal></IonModal>
</IonApp>

so the css selector finds the ion-modal downstream from the ion-page and allows it to show.

When navigating to a different page, it persists this way:

<IonApp>
    <IonModal></IonModal>
    <IonPage name='newPage'></IonPage>
</IonApp>

so the modal is no longer downstream from an ion-page, and it gets display: none.

This works, but surely there is a way to stop the ion modal from persisting through all pages after it is initialized, right?

When you set backdropDismiss={false}, you are taking responsibility for dismissing the modal. The modal isn’t getting hidden automatically because you need to dismiss it by changing the value of isOpen.

To say it a different way, if isOpen={true}, shouldn’t the modal be open?

So an easy way to fix this is to structure the modal something like this:

const [showModal, setShowModal] = useState(false);

....

<IonModal
    isOpen={showModal}
    backdropDismiss={false}
  >
  {children}
</IonModal>

And then call setShowModal(false) when you want to hide the modal.

1 Like

Thanks for the response! Yes this is what I got working.