Hello World Master

Tutorials, articles and quizzes on Software Development

Ionic React > Articles

Using IonFabButton and IonModal to make Todo items in Ionic React

This article is associated with the following course
Introduction to Ionic React

In our Ionic React application, we’re going to want to add a IonFabButton that opens up a model

Adding the IonFabButton

We’re going to want to add an IonFab component thats wrapped around our IonFabButton. We want to set the slot prop equal to fixed, and for this example we want our fab button to be on the bottom right.

<IonPage>
  <IonToolbar>
      <IonTitle>Todo App</IonTitle>
    </IonToolbar>
  <IonContent>
    <IonGrid>
      {todoItems.map((todoItem, index) => (
        <IonRow>
          <IonCol size="12">
            <IonItem>
              <IonGrid>
                <IonRow>
                  <IonCol size-xs="8.5" size-sm="8.5" size-md="10" size-lg="11"  class="ion-align-self-center">
                    <IonText>{todoItem.title}</IonText>
                  </IonCol>
                  <IonCol size-xs="3.5" size-sm="3.5" size-md="2" size-lg="1" class="ion-text-right">
                    <IonButton onClick={() => deleteTodo(index)}>Delete</IonButton>
                </IonCol>
                </IonRow>
              </IonGrid>
            </IonItem>
          </IonCol>
        </IonRow>
      ))}
    </IonGrid>
    <IonFab slot="fixed" vertical="bottom" horizontal="end">
      <IonFabButton></IonFabButton>
    </IonFab>
  </IonContent>
</IonPage>

Adding the Modal with the IonModal component

We want to add our IonModel component. It doesn’t matter where inside our component we place it, since it will overlay over everything else, but lets put it at the bottom, next to the IonFabButton

...
<IonModal>
  <p>Some content inside our Model</p>
</IonModal>
<IonFab slot="fixed" vertical="bottom" horizontal="end">
  <IonFabButton>Add Todo</IonFabButton>
</IonFab>
...

Our modal wont show up unless we pass down a prop named isOpen to our IonModel component and the model must be set to true.

To handle this, we’re going to create use the useState hook and have it toggled using the IonFabButton we created.

..
const Todo = () => {
  const [showModal, setShowModal] = useState(false);
... 
...
<IonModal isOpen={showModal}>
  <p>This is modal content</p>
  <IonButton onClick={() => setShowModal(false)}>Close Modal</IonButton>
</IonModal>
<IonFab slot="fixed" vertical="bottom" horizontal="end">
 <IonFabButton onClick={()=>setShowModal(true)}>Add Todo</IonFabButton>
</IonFab>
...

Note that we also have a button in the model so we can close the model and go back to our page.

Now when you click the Fab button, the model will appear, and when you click the IonButon inside the modal, the Model will disappear.

On desktop, the modal will be much smaller, centered in the middle of the viewport with a dark transparent overlay behind it. Here, you could click any part of the overlay to close the modal