Alerts in LWC (Lightning Web Component)

This post will walk you through the implementation of using alerts in LWC (Lightning Web Component) using LightningAlert adapter of lightning/alert.

We can use alerts in LWC instead of the native and old fashioned window.alert() for a more consistent user experience. It has similar functionalities, but this works in cross-origin iframes, where the alert() method is no longer supported in most browsers.

Let’s directly get into the implementation.

Implementation

Create a Lightning Web Component named alertsLwc. First, simply add a button in the component that will call the Javascript method. This is how your HTML file would look like:

alertsLwc.html

<template>
    <lightning-card  title="Alerts in LWC">
        <div class="slds-p-around_small">
            <lightning-button variant="brand" onclick={handleButtonClick} label="Show Alert"></lightning-button>
        </div>
    </lightning-card>
</template>

Once, the Show Alert button is clicked, it will call the handlButtonClick method from the JavaScript controller.

In the JavaScript file, we first need to include the LightningAlert adapter from the lightning/alert module. In the handlButtonClick, use LightningAlert.open method with the below parameters to show the alert:

  • message: The error message for the alert.
  • theme: type of the alert. In this case, it is an error.
  • label: This is the header of the alert.

These are the minimum parameters that we need to send to LightningAlert.open method.

There are more optional parameters that we can send, which you can check in the Salesforce official documentation for Alerts in LWC (Lightning Web Component).

Also Read:

This is how our JavaScirpt file would look like:

alertsLwc.js

import { LightningElement } from 'lwc';
import LightningAlert from 'lightning/alert';

export default class AlertsLwc extends LightningElement {
    async handleButtonClick() {
        await LightningAlert.open({
            message: 'This is the test alert message',
            theme: 'error',
            label: 'Error!'
        });
    }
}

Alerts in LWC (Lightning Web Component)

This is how our output would look like after clicking the button:

alerts in lwc (Lightning Web Component) using LightningAlert
Alerts in LWC (Lightning Web Component)

That is all from this post. This is how we can use Alerts in LWC (Lightning Web Component). Please Subscribe Here if you don’t want to miss new implementations.

Thank you for reading. See you in the next implementation!

Leave a Comment