Show Toast message in LWC

It's pretty much straight forward to fire up a toast message in LWC. Let's understand how to customise it.

I say this time and again, as far as the concepts are concerned it's the same in both in Aura and LWC.

In Aura components we have Navigation and we do have the same navigation concept in LWC. Same is the case with Events, Lightning Message Service and etc.

Let's talk a bit about how to fire toast messages in LWC.

On the template file am gonna have a button and on click of the button, it will trigger a function.

<template>
    <lightning-button label="Show Toast" onclick={showNotification}></lightning-button>
</template>
exploreToast.html

Here is the JS controller.

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

export default ExploreToast extends LightningElement{
        showNotification() {
        const evt = new ShowToastEvent({
            title: 'This is the Title',
            message: 'Record is saved successfully!',
            variant: 'success',
        });
        this.dispatchEvent(evt);
    }
}    
exploreToast.js

It's a mandate that we import the named import ShowToastEvent from the package lightning/platformShowToastEvent.

Once the named import is imported after that it's all about passing the right params.

In the above example, you would have noticed that I have passed values for title, message, variant keys.

Few other values that we can pass for variant are info, warning, error along with success.

Along with that, I can also pass values for messageData and mode.

Hope it was helpful!