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
1. Import ShowToastEvent
To use toast messages, you need to import the ShowToastEvent
 class from the lightning/platformShowToastEvent
 module.
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
2. Create a Method to Dispatch the Toast Event
Next, 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
}
3. Trigger the Toast Message
You can trigger the toast message by calling the showToast
method from a button click or any other event.
Customizing Toast Messages
The ShowToastEvent supports the following properties:
title : The heading of the toast message.
message : The detailed message to display.
variant : The type of toast. Options include:
success
 (green background)error
 (red background)warning
 (yellow background)info
 (blue background)
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',
})
);
}
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.
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!