Lightning Web Component(LWC) Toast Messages

Lightning Web Component(LWC) Toast Messages

LWC Toast Messages

Lightning Web component(LWC) can send a toast notification that pops up to alert users of success, error or warning. A toast can also simply provide information. To display a toast notification in Lightning Experience or Lightning communities, import ShowToastEvent from the lightning/platformShowToastEvent module. We can dispatch this toast on some event like click of button.

 

How to add toast message in Lightning Web component(LWC)

Import Toast Message

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

Dispatch toast Message

showToast() {
    const event = new ShowToastEvent({
        title: 'Toast message',
        message: 'Toast Message',
        variant: 'success',
        mode: 'dismissable'
    });
    this.dispatchEvent(event);
}

 

Here are some point about toast message:

  • We can style toast to provide error, success, warning and information message using mode parameter.
  • We can also configure the visibility of the toast using variant. It can remain visible for three seconds, until the user clicks to dismiss it, or a combination of both.
  • To trigger a toast from a Lightning web component, in the component’s JavaScript class, import ShowToastEventfrom lightning/platformShowToastEvent.
  • Create a ShowToastEvent with a few parameters, and dispatch it.

Types of toast messages Lightning Web Component(LWC)

Error Toast

showErrorToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Error',
        message: 'Some unexpected error',
        variant: 'error',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Success Toast

showSuccessToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Success',
        message: 'Opearion sucessful',
        variant: 'success',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Warning Toast

showWarningToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Warning',
        message: 'Some problem',
        variant: 'warning',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Info Toast

showInfoToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Info',
        message: 'Operation will run in background',
        variant: 'info',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

LWC Toast Messages Example

toastNotificationExampleLWC.html

<template>
    <lightning-card title="Notification" icon-name="custom:custom19">
        <lightning-button label="Show Error" onclick={showErrorToast}></lightning-button>
        <lightning-button label="Show Success" onclick={showSuccessToast}></lightning-button>
        <lightning-button label="Show Warning" onclick={showWarningToast}></lightning-button>
        <lightning-button label="Show Info" onclick={showInfoToast}></lightning-button>
    </lightning-card>
</template>

toastNotificationExampleLWC.js

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastNotificationExampleLWC extends LightningElement {
    showErrorToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Error',
            message: 'Some unexpected error',
            variant: 'error',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showWarningToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Warning',
            message: 'Some problem',
            variant: 'warning',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showInfoToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Info',
            message: 'Operation will run in background',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}

toastNotificationExampleLWC.js-meta.xml

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

Now we can add this LWC component on the home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your toastNotificationExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

Lightning Web component(LWC) Toast Messages

 

Here is list of Toast Event Parameters:

PARAMETERTYPEDESCRIPTION
titleStringThe title of the toast, displayed as a heading.
messageStringA string containing a message for the user.
messageDataString[] or Objecturl and label values that replace the {index} placeholders in the message string.
variantStringThe theme and icon displayed in the toast. Valid values are:

info—(Default) A gray box with an info icon.
success—A green box with a checkmark icon.
warning—A yellow box with a warning icon.
error—A red box with an error icon.
modeStringDetermines how persistent the toast is. Valid values are:

dismissable—(Default) Remains visible until the user clicks the close button or 3 seconds has elapsed, whichever comes first.
pester—Remains visible for 3 seconds.
sticky—Remains visible until the user clicks the close button.

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-web-component-lwc-toast-messages/

6 comments

Skip to comment form

    • Sidney on May 20, 2020 at 8:10 am

    Hi Ankush,

    This is very helpful. I have one question though, how do we display field errors (validation error) on the Toast message? I’m not sure if I have the syntax correctly but this is what I use:

    this.dispatchEvent(
    new ShowToastEvent({
    title: ‘Error updating record’,
    message: this.error.message,
    variant: ‘error’
    })
    )

    Unfortunately, the message shows as undefined. Any thoughts?

    1. Your code seems to be correct. Can you please post your full code. It will help in checking exact error. Did you trying copy pasting exact code from this post?

        • Sidney on May 20, 2020 at 2:29 pm

        Hi Ankush,

        Thanks for responding. The code came from my end. I was trying to display the “catched” field errors (aka Validation Rule error) and display them in my Toast. By the way, it was “this.error.body.message” not the one in the initial post. Here is my code, please take a look.

        handleSave(){

        saveAccountsLwc({records : this.myList, opptyId : this.searchKey})
        .then(() => {
        this.toggleSaveLabel = ‘Saved’;
        this.dispatchEvent(
        new ShowToastEvent({
        title : ‘Success’,
        message : `Records saved successfully!`,
        variant : ‘success’,
        }),
        )
        this.getAccountRecords();
        this.error = undefined;
        })
        .catch(error => {
        this.error = error;
        this.record = undefined;
        console.log(“Error in Save callback:”, this.error);

        this.dispatchEvent(
        new ShowToastEvent({
        title: ‘Error updating record’,
        message: this.error.body.message,
        variant: ‘error’
        })
        )

        })
        .finally(() => {
        setTimeout(() => {
        this.toggleSaveLabel = ‘Save’;
        }, 3000);
        });
        }
        }

          • Prakhar Gupta on June 10, 2020 at 6:26 pm

          Hey Sidney –
          I ran into the same problem and the solution is
          error.body.output.errors[0].message
          Also, try debugging error.body (console.log(JSON.stringify(error.body)));

    • Lei on June 9, 2020 at 2:02 pm

    Great Help

    • Shruti on July 9, 2020 at 1:53 pm

    Is it possible to trigger this toast when a checkbox value is changed on the account page instead of from a button?

Leave a Reply

Your email address will not be published.