Programmatically calling out an alert doesn't work in Ionic 6 React

In some cases we don’t want to use hooks or JSX to invoke an alert (or toast, loading etc). Using plain JS used to work in Ionic 5 but it stays hidden in the new version (including the official starter templates). Is there anything we could do to fix this?

  const alert = document.createElement('ion-alert');
  alert.header = 'Alert';

  document.body.appendChild(alert);
  alert.present();

Cheers

Hey there! I’m not really sure what the use case is here… If hooks are not your thing… there are the overlay components you can use inline

But I guess to better answer your question, Ionic-React changed how components were bundled internally, so this makes sense. I would not recommend manually adding them to the DOM the way you are trying.

I see, thanks. It is useful to be able to invoke an alert (or some other overlay item) in a function outside the React context. That is, without having to pass down the hook function as a dependency. We have some helper functions that are bundled as separate libraries and whilst before we could just invoke the alerts using vanilla JS, now it requires passing down the hook, sometimes multiple functions down to call it.

This used to work fine in Ionic 4/5 and it looks like it is mostly working for alerts in the v6 so I hoped it could be fixed.

Also, the way I view it, we should be able to revert to using plain JS for any Ionic components regardless of which framework is in use.

Thanks

1 Like

In this Solidsail tutorial, a similar method is used to invoke an app-wide toast helper (for example displaying form validation errors):

Toast helper:

Invocation (line 17):

With current Ionic, the code used in the tutorial gives me an error:

"Uncaught (in promise) TypeError: wrapperEl is null"

in mdEnterAnimation at overlays.js:3813

What would be the correct way to implement the toast helper in current React / Ionic 6 ?

Very true! I used a helper lib in my project to programmatically call the toast, I just upgraded to v6 and now the toast doesn’t work using the JS format. :man_facepalming:t4: Now i have to re-write all toast using components.

There is a difference between an alert and toast… if you have a specific problem maybe if you are looking for help you should post and new question to the forum