Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Build a Modal With Ionic and React

David Dal Busco
Better Programming
Published in
6 min readDec 10, 2019
Photo by timJ on Unsplash

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;

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

David Dal Busco
David Dal Busco

Written by David Dal Busco

Freelancer by day | Creator of Juno.build by night

Responses (1)

Write a response