Using Overlay Components in React
For Ionic React, there are two techniques you can use to display overlay components like modals, alerts, action sheets, etc. In this guide, we will go over both of them.
Overlay Hooks
Starting in Ionic React 5.6, we introduced new React hooks you can use to control displaying and dismissing overlays. These hooks provide a programmatic way of controlling the overlays, as well as a way to use overlays outside of your Ionic Page without the need of a state management system.
To use one of the overlay hooks, you import the hook for the overlay you want to use from @ionic/react
. For example, if we want to use the Alert overlay, we import useIonAlert
:
import { useIonAlert } from '@ionic/react';
The hooks return an array, where the first item in the array is the method to present the hook, and the second is the method to dismiss the hook:
const [showAlert, hideAlert] = useIonAlert();
Overlays often dismiss themselves when the user is done interacting with them, so you might not need to use dismiss/hide method.
To display the overlay, you use the present method, which we destructured to the name showAlert
. The method takes in a set of parameters that vary depending on each overlay, but generally, they can either take in a simple set of common parameters or an object to specify additional options.
showAlert('Hello!', [{ text: 'Ok' }]);
For useIonAlert
, the first parameter is the message to display, and the second is an array of AlertButtons
to customize the buttons the alert will show.
Alternatively, you can pass in an AlertOptions config object to provide additional parameters, such as a CSS class to add to the markup, a header for the alert, and a callback that gets called when the alert is dismissed:
showAlert({
cssClass: 'my-css',
header: 'Alert',
message: 'Hello!',
buttons: ['Cancel', { text: 'Ok', handler: (d) => console.log('ok pressed') }],
onDidDismiss: (e) => console.log('alert dismiss'),
});