DEV Community

Cover image for Introducing the New Overlay Hooks for Ionic React
Ely Lucas for Ionic

Posted on • Originally published at ionicframework.com

Introducing the New Overlay Hooks for Ionic React

Hello Friends! We know everyone is excited about the new features in Ionic Framework 6.0 beta, but that doesn't mean we're done with V5! In Ionic React 5.6, we packaged up a new set of hooks for controlling our overlay components that we think you might like. What is an overlay you ask? It’s the term we give components that display over your current content, such as alerts, modals, toasts, etc.

In this post, I’m going to go over how to use the new hooks to display these components in your apps. But first, let's do a quick recap on how overlays worked before, and some of the challenges that you might encounter with them.

Overlay Components

Each of the overlays has a React component that is exported from @ionic/react, such as IonAlert and IonLoading. These components take a prop called isOpen, which determines if the overlay should be displayed or not:

<IonAlert
  isOpen={showAlert}
/>
Enter fullscreen mode Exit fullscreen mode

These components are great and they aren’t going away. The new hooks don't deprecate them in any way. However, there's some ceremony you have to observe to use them.

First, managing the state that handles the isOpen prop could be a challenge. If the state was contained in the component that the overlay was in, then it was no problem (like a local state variable from useState). However, if the action to display the overlays was in a different part of the app, then you needed to use some state management technique or library to pass the isOpen prop along.

Second, each of the Overlay components required you to provide an onDidDismiss callback that would flip the isOpen prop back to false in case the overlay dismissed itself somehow. Not overriding it would cause isOpen to stay true, and if your app tried to show the overlay again, then you would be setting true to true, and Ionic wouldn’t detect the change and, thus, wouldn't display it again.

<IonAlert
  isOpen={showAlert}
  message='Hello there friend'
  onDidDismiss={() => setShowAlert(false)}
/>
Enter fullscreen mode Exit fullscreen mode

A third challenge was that it was difficult to display an overlay from outside of your component; for instance, if you wanted to display an alert when an API request failed. Ionic Angular had controller instances you could import to use in services to display overlays. In React, this was more difficult to do.

The new overlay hooks in Ionic React 5.6 help with all these scenarios.

Overlay Hooks

The goal of the overlay hooks was to reduce this process and to make the usage of the overlays feel more natural for those writing functional React components.

To get started with the hooks, you import the hook for the overlay you want to use from @ionic/react like so:

import { useIonAlert } from '@ionic/react'
Enter fullscreen mode Exit fullscreen mode

Next, in your functional component, you call the hook to get back the show and hide methods, which get returned in an array similar to how useState returns its members. We choose the array method of destructuring so naming the methods is easier:

const [showAlert, hideAlert] = useIonAlert();
Enter fullscreen mode Exit fullscreen mode

Most overlays dismiss themselves when the user is done interacting with them, so you won’t need the hide method for most scenarios.

Then to display the overlay, you call the show method:

showAlert('Hello!');
Enter fullscreen mode Exit fullscreen mode

The alert will dismiss itself after the user clicks the "Ok" button. You don’t need to worry about doing any additional work when the overlays go away.

Most of the overlay hooks have options that you can pass to them. The more common options can be passed in as additional parameters. For instance, the toast overlay's show method also takes the time to display the toast as its second parameter:

showToast('Hello from a toast!',  3000);
Enter fullscreen mode Exit fullscreen mode

This will display the toast for three seconds, and then the toast will dismiss itself.

More options can be sent by passing in an object instead of the separate parameters:

showToast({
  buttons: [{ text: 'hide', handler: () => hideToast() }],
  message: 'Hello, click hide to dismiss',
  onDidDismiss: () => console.log('dismissed')              
})
Enter fullscreen mode Exit fullscreen mode

React hooks can be used in other hooks as well. Because of this, it's possible to display an overlay from within other hooks, such as one responsible for fetching some data. Here is a sample custom hook to fetch a customer that displays a toast when the request fails:

const useCustomer = (customerId: number) => {
  const [customer, setCustomer] = useState<Customer>();
  const [showToast] = useIonToast();
  useEffect(() => {
    fetchCustomer();
    async function fetchCustomer() {
      try {
        const response = fetch(`myapi.com/customers/${customerId}`);
        const data = await (await response).json();
        setCustomer(data);
      } catch {
        showToast({
          message: 'Oops, unable to get customer',
          color: 'warning',
          buttons: [{ icon: close }],
        });
      }
    }
  }, [customerId, showToast]);
  return customer;
};
Enter fullscreen mode Exit fullscreen mode

More Info

To learn more about the new hooks, visit our guide on using overlays in Ionic React, and check out the docs for each of the overlay components for usage examples:

Let us know in the comments down below if you have any feedback, and until next time, happy coding!

Top comments (0)