Saturday, February 2, 2019

How to Show Toast Notifications in Lightning Web Components(lwc)

This post explains how to show toast notifications in lightning web components(lwc).
To Show the toast notifications in Lighting Web Components, import ShowToastEvent from the lightning/platformShowToastEvent module.

Example:

LwcShowToastNotificationsDemo.html
<template>
    <lightning-card>
        <center>
            <div class="slds-m-top_medium slds-m-bottom_x-large">
                <h2 class="slds-text-heading_medium slds-m-bottom_medium">
                    Show Toast Notifications Demo
                </h2>

                <!-- Button group-->
                <lightning-button-group>
                    <lightning-button label="Show Success" onclick={handleSuccess}></lightning-button>
                    <lightning-button label="Show Error" onclick={handleError}></lightning-button>
                    <lightning-button label="Show Warning" onclick={handleWarning}></lightning-button>
                    <lightning-button label="Show Info" onclick={handleInfo}></lightning-button>
                </lightning-button-group>
            </div>
        </center>
    </lightning-card>
</template>

LwcShowToastNotificationsDemo.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class LwcShowToastNotificationsDemo extends LightningElement {
    handleSuccess() {
        const showSuccess = new ShowToastEvent({
            title: 'Success!!',
            message: 'This is Success message.',
            variant: 'Success',
        });
        this.dispatchEvent(showSuccess);
    }
    
    handleError() {
        const showError = new ShowToastEvent({
            title: 'Error!!',
            message: 'This is Error message.',
            variant: 'error',
        });
        this.dispatchEvent(showError);
    }

    handleWarning() {
        const showWarning = new ShowToastEvent({
            title: 'Warning!!',
            message: 'This is Warning message.',
            variant: 'warning',
        });
        this.dispatchEvent(showWarning);
    }

    handleInfo() {
        const showInfo = new ShowToastEvent({
            title: 'Info!!',
            message: 'This is Info message.',
            variant: 'info',
        });
        this.dispatchEvent(showInfo);
    } 

}

LwcShowToastNotificationsDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="lwcShowToastNotificationsDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output

Happy Learning!!! 

No comments:

Post a Comment