Display Toast Notifications in Lightning Web Components (LWC)

In Salesforce LWC components, we use a toast message to display temporary pop-up notifications on the screen to inform users about an action’s success, failure, or status.

In this Salesforce tutorial, we will learn about the Toast notification feature in LWC and how to display a toast notification in Salesforce Lightning web components.

What Are Toast Notifications in LWC?

In Salesforce, Toast notifications are provided by the lightning/platformShowToastEvent module. The toast message is displayed on screen after a trigger, such as saving records or getting an error. Using the toast notification feature, we can display success, error, info, and warning messages in a pop-up message.

In the LWC toast notification feature, we get four types of toast messages that we display in a pop-up message on the screen.

  • Success: Indicates that an operation was successful.
  • Error: Alerts the user about an issue.
  • Warning: Warns the user about a problem or confirmation.
  • Info: Provides additional information to the user. 

Button modes for displaying toast notification:

The messages are displayed on the screen in three modes, which are dismissible, pester, and sticky. The mode of the message is defined by the mode attribute, such as mode: ‘dismissable’. If the mode is not defined, the message will take dismissible as the default mode.

The function of all three toast message modes is as follows:

  • Dismissable – With this mode, the toast message appears with a close button and remains visible for 5 seconds by default. We can manually close it by clicking the close button before the timer expires. If not closed manually, it auto-closes after 5 seconds.
  • Pester – The pester mode toast appears without a close button and auto-dismisses after 3 seconds. It cannot be closed manually, and is generally used to show info messages or notifications that don’t require interaction.
  • Sticky – When using this mode, the message will be on the screen until we close it, generally used to display error messages.

Displaying Toast Messages in Salesforce LWC Components

To display a toast message in the LWC component, we need to import ShowToastEvent from the lightning/platformShowToastEvent module.

To implement the toast messages in the LWC components, create a LWC component and follow the steps below.

In the example below, we will create an LWC component that displays all toast messages, including success, error, info, and warning.

  1. Create an LWC component and enter the code below in the JS file.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ToastNotifications extends LightningElement {
  
    showSuccessToast() {
        const event = new ShowToastEvent({
            title: 'Success!',
            message: 'Your record has been saved successfully.',
            variant: 'success',
            mode: 'dismissable' 
        });
        this.dispatchEvent(event);
    }

    showErrorToast() {
        const event = new ShowToastEvent({
            title: 'Error!',
            message: 'Error occured, Please try again.',
            variant: 'error',
            mode: 'sticky' 
        });
        this.dispatchEvent(event);
    }

    showWarningToast() {
        const event = new ShowToastEvent({
            title: 'Warning!',
            message: 'Data is incomplete.',
            variant: 'warning',
            mode: 'pester' 
        });
        this.dispatchEvent(event);
    }

    showInfoToast() {
        const event = new ShowToastEvent({
            title: 'Info',
            message: 'This is a notification for your information.',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(event);
    }
}

In this, we first imported the toast notification feature from Lightning by using the method import{ ShowToastEvent } from ‘lightning/platformShowToastEvent’. After this, we created events to define the toast messages that will trigger on button click.

For the toast messages, we defined the attributes title for the message title, message for the custom message text, variant to define the toast notification icon (warning, success, error, and info) and notification mode.

  1. After defining the toast notification logic, enter the code below in the HTML file to render the UI of buttons through which we will trigger and display toast notifications.
<template>
    <lightning-card title="Toast Notifications">
        <div class="slds-p-around_medium">
            <lightning-button label="Show Success Toast" variant="brand" onclick={showSuccessToast}></lightning-button>
            <lightning-button label="Show Error Toast" variant="destructive" onclick={showErrorToast}></lightning-button>
            <lightning-button label="Show Warning Toast" variant="neutral" onclick={showWarningToast}></lightning-button>
            <lightning-button label="Show Info Toast" variant="base" onclick={showInfoToast}></lightning-button>
        </div>
    </lightning-card>
</template>

In this HTML file, we have defined the buttons UI through which we will call the events to display the toast notifications using onclick={showSuccessToast} and other onclick events.

We have also defined variants for the buttons, such as brand for the success button, destructive for the red error button, neutral for the warning with white button, and a base variant to display the info toast message.

  1. Enter the code below in the meta.xml file inside the Lightning component bundle tag to make the LWC component available for the Lightning pages.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Deploy the LWC component to the Lightning page, and there you will see buttons in the UI of the LWC component.
Salesforce LWC Toast Notifications

As we click on the button, it will call the assigned event and display toast notifications accordingly.

Display Toast Notifications in LWC Components

This way, we can display toast notifications in the LWC component using the platformShowToastEvent and defining events to call them through a trigger or a button.

Create Reusable Toast Notification Utility

In Salesforce, displaying toast notifications is required for many use cases, so instead of defining all the attributes of the toast events repeatedly for each time you want to display a toast notification, we can create a reusable toast notification utility component.

With this, we can export the toast feature in another LWC component to define the toast notifications.

Follow the steps below to create a reusable utility component for toast notifications.

  1. Create a new LWC component and enter the code below in the JS file. Since it is a utility component, we don’t need to define UI in HTML and expose it to Lightning pages via meta.xml code.
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export function showToast(component, title, message, variant, mode = 'dismissable') {
    const event = new ShowToastEvent({
        title,
        message,
        variant,
        mode
    });
    component.dispatchEvent(event);
}

In this component, we have imported the ShowToastEvent from Lightning and defined all attributes: title, message, variant, and mode in a function. We have also defined the default notification of toast messages using mode = ‘dismissable’.

  1. To use this toast notification utility component, we have to import it into the LWC component, which is where we use the toast notification feature.

To import this utility component, we can define the JS code of the LWC component as follows.

import { LightningElement } from 'lwc';
import { showToast } from 'c/toastUtility';

export default class ToastDemo extends LightningElement {
    showSuccessToast() {
        showToast(this, 'Success!', 'Your record has been saved successfully.', 'success');
    }

    showErrorToast() {
        showToast(this, 'Error!', 'Something went wrong. Please try again.', 'error', 'sticky');
    }

    showWarningToast() {
        showToast(this, 'Warning!', 'Proceed with caution.', 'warning', 'pester');
    }

    showInfoToast() {
        showToast(this, 'Info', 'This is a neutral notification.', 'info');
    }
}

In this component, we first import the utility component using import { showToast } from ‘c/toastUtility’.

In this, we don’t need to define the attributes of the toast notifications, such as title, message, variant, and mode. We just need to assign the values of the attributes in an order. For example, to display a success toast, we will define it as below.

showSuccessToast() {
        showToast(this, 'Success!', 'Your record has been saved successfully.', 'success');
    }

In this, we have defined the values of title, message, and variant. If we don’t include the mode value, it will take the default dismissible mode.

This way, we can create a reusable utility component for the lighting toast notifications.

Use Case Scenario to Display Toast Notifications in LWC Component

In the example below, we will see a real-time use case of displaying a toast message on the Lightning Web Components.

Through this LWC component, we will create account records with field input of Account name, with the following toast messages.

  • Success – When entering a valid account name and saving the record.
  • Warning – If the account name includes “test” in the name.
  • Error – When the account name contains numbers or it is blank.
  • Info – When the account is saved, the info toast message will show the created account’s ID.

Follow the steps below to create an LWC component that will display toast messages according to the above conditions.

  1. First, we need to create a controller class that will save the account records in the database and handle exceptions for blank input, which will show an error.
public with sharing class AccountController {
    @AuraEnabled
    public static String createAccount(String accountName) {
        try {
            if (String.isBlank(accountName)) {
                throw new AuraHandledException('Account name cannot be blank.');
            }
            
            Account acc = new Account(Name = accountName);
            
            return acc.Id;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}
  1. Create an LWC component accountCreator and enter the code below in the JS file to define the logic of displaying toast notifications and saving the account record.
import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import createAccount from '@salesforce/apex/AccountController.createAccount';

export default class AccountCreator extends LightningElement {
    @track accountName = '';

    handleNameChange(event) {
        this.accountName = event.target.value;
    }

    async handleSave() {
        try {
            if (this.accountName.toLowerCase().includes('test')) {
                this.showWarningToast();
                return;
            }
            if (/\d/.test(this.accountName)) {
                this.showErrorToast('Account name cannot contain numbers.');
                return;
            }

            const accountId = await createAccount({ accountName: this.accountName });
            this.showSuccessToast(accountId);
            this.showInfoToast(accountId);

        } catch (error) {
            this.showErrorToast(error.body.message);
        }
    }

    showSuccessToast(accountId) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success!',
                message: 'Account created with ID: ${accountId}',
                variant: 'success',
                mode: 'dismissable'
            })
        );
    }

    showErrorToast(errorMessage) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error!',
                message: errorMessage || 'Failed to create account.',
                variant: 'error',
                mode: 'sticky'
            })
        );
    }

    showWarningToast() {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Warning!',
                message: 'Account name contains "Test" - Enter valid name',
                variant: 'warning',
                mode: 'pester'
            })
        );
    }

    showInfoToast(accountId) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Info',
                message: 'Account Number will be generated soon for ID: ${accountId}',
                variant: 'info',
                mode: 'dismissable'
            })
        );
    }
}

In this code, we have defined the logic for saving the record. When the user clicks on save after entering input, the handleNameChange event triggers, checking the input and returning the toast messages according to that.

  1. Enter the code below in the HTML file to render the UI of the LWC component and toast messages.
<template>
    <lightning-card title="Create Account" >
        <div class="slds-p-around_medium">
            <lightning-input 
                label="Account Name" 
                value={accountName} 
                onchange={handleNameChange} 
                placeholder="Enter account name">
            </lightning-input>
            <div class="slds-m-top_small">
                <lightning-button 
                    label="Save Account" 
                    variant="brand" 
                    onclick={handleSave}>
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>

The onchange attribute calls the event that checks the input for the entered name, and the handleSave event saves the records. If a valid input is given, it will return success and info; otherwise, it will return an error and a warning toast notification.

  1. Expose the LWC component to the lighting page by entering the code below in the meta.xml file inside the <LightningComponentBundle> tag.
<targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
 </targets>
  1. Deploy the LWC component to the Lightning page, using the Lightning App Builder.
  1. When the user gives input to create an account and clicks Save, it will trigger the event to display the toast messages according to the above-mentioned conditions.

For Success and Info toast message:

How to display Toast Notification in LWC component

For warning toast message:

Display warning toast message in LWC component

For Error Toast message:

Display Error Toast Notification in LWC component

The toast message is displayed on the screen according to the provided input values. This way, we can apply conditional logic to trigger and display the toast notification in Lightning Web Components.

Conclusion

In this Salesforce tutorial, we have learned about the Lightning toast notification feature, and we created an LWC component in which we learned how to set up the Lightning toast notification by defining the attributes of the toast message and triggering them using events.

After this, we also created a reusable utility component to call the toast message from this component to other components whenever required. At last, we used a real-time example, creating accounts using LWC and displaying toast messages according to the defined conditions.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.