Create Notifications in LWC using New Alert, Confirm, and Prompt Modules | Summer '22 | Salesforce LWC Stack ☁️⚡️

 In this blog I will show you how you can create notifications using New Alert, Confirm and Prompt modules in a Lightning Web Component.

The modules can be accessed right inside your existing Lightning Web Components. For example, to use the alert component, you will just need to import LightningAlert from lightning/alert.

To open the alert, you can then just call LightningAlert.open().

Use the new modules LightningAlert, LightningConfirm, and LightningPrompt instead of native APIs to create notifications from your Lightning web components. Chrome and Safari plan to end support for cross-origin use of the window.alert(), window.confirm(), and window.prompt() native APIs. Each new module creates a modal that functions like its API counterpart and works in cross-origin iframes.

In below example I have created 3 buttons in a custom LWC to display Alert, Confirm and Prompt notification.

Please check below code and output -


HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<template>
  <lightning-card title="Notifications" icon-name="utility:user">
    <div class="slds-box">
      <lightning-button label="Alert" onclick={handleAlert}></lightning-button>
      <br />
      <br />
      <lightning-button
        label="Confirm"
        onclick={handleConfirm}
      ></lightning-button>
      <br />
      <br />
      <lightning-button
        label="Prompt"
        onclick={handlePrompt}
      ></lightning-button>
    </div>
  </lightning-card>
</template>


JS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { LightningElement } from "lwc";
import LightningAlert from "lightning/alert";
import LightningPrompt from "lightning/prompt";
import LightningConfirm from "lightning/confirm";

export default class LightningNotifications extends LightningElement {
  async handleAlert() {
    await LightningAlert.open({
      message: "Sample Alert Message",
      theme: "error",
      label: "Alert Header"
    }).then(() => {
      console.log("###Alert Closed");
    });
  }
  async handleConfirm() {
    const result = await LightningConfirm.open({
      message: "Sample Confirm Message",
      theme: "success",
      label: "Confirm Header"
    });
    console.log("🚀 ~ result", result);
  }
  handlePrompt() {
    LightningPrompt.open({
      message: "Sample Prompt Message",
      theme: "error",
      label: "Prompt Header",
      defaultValue: "Test"
    }).then((result) => {
      console.log("🚀 ~ result", result);
    });
  }
}


Output



Please checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments