How to Implement Toast Messages in Lightning Web Components (LWC)

How to Implement Toast Messages in Lightning Web Components (LWC)
Chinmaya By Chinmaya
6 Min Read

Introduction

Toast messages are a great way to provide feedback to users in Salesforce Lightning Web Components (LWC). They are non-intrusive, temporary notifications that appear at the top of the screen.

In this blog post, we’ll walk through how to implement toast messages in LWC step by step.

What is a Toast Message?

A toast message is a small notification that appears on the screen to inform users about the success, failure, or status of an action.
In LWC, toast messages can be customized with different variants like – success, error, warning and info.

Steps to Implement Toast Messages in LWC

Step 1 - Import ShowToastEvent

To use toast messages, you need to first import the ShowToastEvent class from the lightning/platformShowToastEvent module.

				
					import { ShowToastEvent } from 'lightning/platformShowToastEvent';
				
			

Step 2 - Create a Toast Event

Next step, create a method that dispatches the ShowToastEvent. This method will define the toast message’s title, message, variant, and mode.

				
					showToast() {
    const event = new ShowToastEvent({
        title: 'Success', // Title of the toast
        message: 'Record updated successfully!', // Message to display
        variant: 'success', // Variant: 'success', 'error', 'warning', or 'info'
        mode: 'dismissable' // Optional: 'dismissable' or 'pester'
    });
    this.dispatchEvent(event); // Dispatch the event to show the toast
}
				
			

Step 3 - Trigger the Toast Message

You can trigger the toast message by calling the showToast method from a button click or any other event.

				
					<template>
    <lightning-button label="Show Toast" onclick={showToast}></lightning-button>
</template>
				
			

Complete Example Component

Here’s a complete component that shows a toast when a button is clicked:

				
					<!-- toastExample.html -->
<template>
    <lightning-card title="Toast Message Example">
        <div class="slds-p-around_medium">
            <lightning-button 
                label="Show Success Toast" 
                variant="brand"
                onclick={showSuccessToast}
            ></lightning-button>
        </div>
    </lightning-card>
</template>
				
			
				
					// toastExample.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ToastExample extends LightningElement {
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Success',
            message: 'Operation completed successfully',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}
				
			

Customizing Toast Messages

The ShowToastEvent supports the following properties:

    1. title : The heading of the toast message.

    2. message : The detailed message to display.

    3. variant : The type of toast. Options include:

      • success (green background)

      • error (red background)

      • warning (yellow background)

      • info (blue background)

    4. mode : Controls how the toast behaves:

      • dismissable (user can manually close the toast)

      • pester (toast remains visible for a longer time)

Example: Displaying Different Types of Toasts

Here’s an example of how to display different types of toast messages:

				
					showSuccessToast() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Success',
            message: 'Operation completed successfully!',
            variant: 'success',
        })
    );
}

showErrorToast() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Error',
            message: 'Something went wrong!',
            variant: 'error',
        })
    );
}
				
			

Advanced Toast Features

You can include a link in your toast message:

				
					showToastWithLink() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Record Created',
            message: 'New account {0} created',
            messageData: [
                {
                    url: '/lightning/r/Account/001xx000003DGg0AAG/view',
                    label: 'Acme Corporation'
                }
            ],
            variant: 'success'
        })
    );
}
				
			

2. Persistent Toast

Make the toast stay until dismissed by the user:

				
					showPersistentToast() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Important Notice',
            message: 'This message requires your attention',
            variant: 'warning',
            mode: 'sticky' // stays visible until dismissed
        })
    );
}
				
			

3. Custom Duration

Control how long the toast is visible (in milliseconds):

				
					showCustomDurationToast() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Auto-close in 10 seconds',
            message: 'This toast will disappear after 10 seconds',
            variant: 'info',
            mode: 'pester',
            duration: 10000 // 10 seconds
        })
    );
}
				
			

Practical Use Cases

1. After Record Update

				
					async handleSave() {
    try {
        await updateRecord(this.recordInput);
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: 'Record updated successfully',
                variant: 'success'
            })
        );
    } catch (error) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error saving record',
                message: error.body.message,
                variant: 'error'
            })
        );
    }
}
				
			

2. Form Validation Feedback

				
					validateForm() {
    if (!this.inputValue) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Missing Information',
                message: 'Please fill in all required fields',
                variant: 'error'
            })
        );
        return false;
    }
    return true;
}
				
			

3. Action Confirmation

				
					handleDelete() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Deleted',
            message: 'The record has been deleted',
            variant: 'success'
        })
    );
    // Navigate away or refresh data
}
				
			

When to Use Toast Messages

    • To confirm successful actions (e.g., record updates).

    • To notify users of errors or warnings.

    • To provide informational messages without interrupting the user’s workflow.

Best Practices for Toast Messages

    1. Be Concise: Keep messages short and actionable.

    2. Use Appropriate Variants: Match the message type to the situation.

    3. Don’t Overuse: Avoid showing toasts for every minor action.

    4. Provide Context: Include enough information for users to understand.

    5. Consider Timing: For sequences, space out toasts to avoid overlap.

    6. Test on Mobile: Ensure toasts display properly on all devices.

Conclusion

Toast messages are a simple yet powerful way to communicate with users in LWC.
By using the ShowToastEvent class, you can easily implement and customize toast messages to enhance the user experience in your Salesforce applications. Give it a try in your next LWC project!

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment