Toast with Ionic React

Posted on March 28, 2020

A toast notification is a long standing custom in mobile application used to notify the user of something happening within the system. Sometimes it even has buttons for interaction.

Toast GIFc

Here is how to use one (straight from the docs):

1function ToastExample: FC = () => {
2 const [showToast, setShowToast] = useState(false);
3 return (
4 <IonToast
5 isOpen={showToast}
6 onDidDismiss={() => setShowToast(false)}
7 message="Your settings have been saved."
8 duration={200}
9 />
10 )
11}

Well, this is easy 😁I can do that.

But I normally thinks of toasts more imperatively than this. It might be because of libraries like react-toast or ant.design who have these imperative toast messaging systems, or it could even be that Ionic’s own Angular part of design has an imperative toast.

Also, if I needed to a success toast and an error toast, I would need multiple IonToast components rendered or have states definining toast state.

In Angular Ionic, you would:

const toast = this.toastController.create({
message: '',
});
toast.present();

That’s pretty cool 😎. What if we could do this?

We could utilise a React Context and a hook to achieve this functionality at with ease. I wrote out a custom package which does exactly that.

1import { ToastProvider, useToast } from "@agney/ir-toast";
2
3// Wrap you App.tsx with ToastProvider
4const App: FC = () => {
5 <IonApp>
6 <ToastProvider>
7 // ...rest of your application
8 </ToastProvider>
9 </IonApp>
10}
11
12// In your component
13const RegisterForm: FC () => {
14 const Toast = useToast();
15 // ...
16
17 function validate() {
18 const toast = Toast.warning('Passwords don\'t match');
19 }
20
21 function submit(data) {
22 try {
23 const response = await api.register(data);
24 Toast.success('Registration Successful');
25 } catch() {
26 Toast.error('Request failed');
27 }
28 }
29}

This allows you have to have error messages with a one liner:

Toast.error('Error message');

The ToastProvider also takes a value property that allows you to define defaults for all toasts created in it’s children.

The package also enables creating toast messages with the same Angular API as:

1function Component: FC = () => {
2 const Toast = useToast();
3
4 const handleClick = () => {
5 const toast = Toast.create({ message: 'thing' });
6 toast.present();
7 // When you want to.
8 toast.dismiss();
9 ...
10 }
11
12 // ...
13}

To install the package:

npm i @agney/ir-toast

Note that it has a dependency on both React and Ionic React.

Github for Full Source

Buy me a coffeeBuy me a coffee