Member-only story
How To Build a Modal With Ionic and React
How to declare and pass parameters to an Ionic + React modal

I’m having fun with Ionic React these days and am, therefore, experimenting with different components.
One of these, which I use almost without exception in all applications, is the modal.
Although its dedicated documentation is pretty neat, I went a bit further, as I like to declare them in their own separate components. That’s why I’m writing this new blog post.
Getting Started
To add a modal to an application, we proceed as displayed in the documentation (told you, it is well-documented).
We use the component IonModal
and, to trigger its opening and closing, we also use a state (with the help of a useState
Hook) to modify its property isOpen
.
import React, { useState } from 'react';
import { IonModal, IonButton, IonContent } from '@ionic/react';
export const Tab1: React.FC = () => {
const [showModal, setShowModal] = useState(false);
return (
<IonContent>
<IonModal isOpen={showModal}>
<p>This is the modal content.</p>
<IonButton onClick={() => setShowModal(false)}>
Close Modal
</IonButton>
</IonModal>
<IonButton onClick={() => setShowModal(true)}>
Show Modal
</IonButton>
</IonContent>
);
};
export default Tab1;
Note that I have used the tab
starter kit to develop this article, that’s why the above page’s name is Tab1
.
Create a Component
Modals could quickly become as complicated as pages. That’s why I am used to declaring them in their own components. Let’s then try to create a new one in a separate new file, called, for example, MyModal.tsx
.
import React from 'react';
import {IonHeader, IonContent, IonToolbar, IonTitle} from '@ionic/react';
class MyModal extends React.Component {
render() {
return <>
<IonHeader>
<IonToolbar color="primary">
<IonTitle>My Modal</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<p>This is the modal content.</p>
</IonContent>
</>
};
}
export default MyModal;