How do I fire a snackbar notice in admin?

I have a custom plugin and want it on occasions to fire the kind of notice that appears and disapears in the left corner like this one:

snackbar notice

I found some code in the Gutenberg docs here:

const MySnackbarNotice = () => (
 <Snackbar>
    Post published successfully.
 </Snackbar>
);

But adding this to my admin-enqueued js script obviously doesn’t work.

Thanks!

2 Answers
2

WordPress has some global actions you can use here. If you want to add your own notice in the lower corner (like the screenshot), you can do that like this:

 wp.data.dispatch("core/notices").createNotice(
        "success", // Can be one of: success, info, warning, error.
        "This is my custom message.", // Text string to display.
        {
          type: "snackbar",
          isDismissible: true, // Whether the user can dismiss the notice.
          // Any actions the user can perform.
          actions: [
            {
              url: '#',
              label: 'View post',
            },
          ],
        }
      );

The important part here is type: "snackbar". You can also leave out the snackbar part and it will appear in the UI above the content:

enter image description here

Here’s the full article on WordPress’ Block Editor Handbook: https://developer.wordpress.org/block-editor/tutorials/notices/

Leave a Comment