Skip to main content

Custom Toast Message in LWC with custom duration

How to show custom Toast message in LWC and increase the duration or length of the time the toast is visible ?


Show custom Toast message

In Salesforce we have base component to show Toasts to the user. Toasts are used to provide feedbacks to user to show success or error messages of the action taken. For example after a record is updated or a new record is created. 

Currently, in base component the toast remains visible to the user on the screen only for 3 seconds by default and user can configure it to dismiss it on click or a combination of both. 

However, in LWC user cannot increase the duration of the toast to be visible to the user for more than the default time which is 3 seconds. In Aura Component this is possible, a developer can configure the duration or length of the toast according to the requirement.

What if we have a requirement to increase the duration and it is a LWC component ? In this post we will see how we can create a custom Toast component in LWC to configure the duration of the toast .

 To achieve this we can create a custom component instead of importing the standard (import ShowToastEvent from lightning/platformShowToastEvent)

Steps to follow

We will follow 2 simple steps to configure the duration.

Steps:-

Step 1. Create a custom component - customShowToastMessage and configure the Javascript file with a function to accept the following parameters-
  • Title
  • Message
  • Variant
  • Duration
  • Auto Close
Step 2. Include this customShowToastMessage LWC component in your own LWC component where you want to show a feedback/notification to user for more than 3 seconds.

customShowToastMessage.html
<template>
    <div data-id="modalToast" style="height: 0rem;" class="slds-hide">
        <div class="slds-notify_container">
            <div id='variantClass' class={variantClass} role="status">
                <span class="slds-assistive-text">{variant}</span>
                <span class={messageClass} title={message}>
                <lightning-icon icon-name={iconName} size="small" variant="inverse"></lightning-icon>
                </span>
                <div class="slds-notify__content">
                    <h2 class="slds-text-heading_small ">{title}</h2>
                    <h2 class="slds-text-heading_small ">{message}</h2>
                </div>
                <div class="slds-notify__close">
                    <button class="slds-button slds-button_icon slds-button_icon-inverse" title="Close" onclick={closeModal}>
                        <lightning-icon icon-name="utility:close" size="small" variant="inverse"> </lightning-icon>
                        <span class="slds-assistive-text">Close</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>


customShowToastMessage.js
import {LightningElement, api} from 'lwc';
export default class CustomShowToastMessage extends LightningElement {
    title;
    message;
    duration;
    autoClose;
    variant;
    myTimeout;

    @api
    showCustToastEvent(event) {
        this.title = event.detail.title;
        this.message = event.detail.message;
        this.variant = event.detail.variant;
        if(event.detail.isAutoClose !== undefined && event.detail.isAutoClose !== '' && event.detail.isAutoClose !== null){
            this.autoClose = event.detail.isAutoClose ;
        }
        if(event.detail.duration !== undefined && event.detail.duration !== '' && event.detail.duration !== null){
            this.duration = event.detail.duration ;
        }
        this.duration = this.duration * 1000;
        const modalToast = this.template.querySelector('[data-id="modalToast"]');
        modalToast.className = 'slds-show';

        if (this.autoClose){
            this.myTimeout = setTimeout(() => {
                this.closeModal();
            }, this.duration);
        }        
    }

    closeModal() {
        clearTimeout(this.myTimeout);
        const modalToast = this.template.querySelector('[data-id="modalToast"]');
        modalToast.className = 'slds-hide';
    }

    get variantClass(){
        return 'slds-notify slds-notify_toast' + ' slds-theme_' + this.variant;
    }
   
    get messageClass(){
        return 'slds-icon_container' + ' slds-icon-utility-' + this.variant + ' slds-icon-utility-success slds-m-right_small slds-no-flex slds-align-top' ;
    }

    get iconName() {
        return 'utility:' + this.variant;
    }
}


In customShowToastMessage.js we have below showCustToastEvent public function. This function is the main function which holds the values. We will pass event from our test component to use the toast.
@api
    showCustToastEvent(event) {
        this.title = event.detail.title;
        this.message = event.detail.message;
        this.variant = event.detail.variant;
        if(event.detail.isAutoClose !== undefined && event.detail.isAutoClose !== '' && event.detail.isAutoClose !== null){
            this.autoClose = event.detail.isAutoClose ;
        }
        if(event.detail.duration !== undefined && event.detail.duration !== '' && event.detail.duration !== null){
            this.duration = event.detail.duration ;
        }
        const modalToast = this.template.querySelector('[data-id="modalToast"]');
        modalToast.className = 'slds-show';

        if (this.autoClose){
            this.myTimeout = setTimeout(() => {
                this.closeModal();
            }, this.duration);
        }        
    }

Now, after creating customShowToastMessage let us create a component to call the showToast and test it out.
Create customToastComp_Test component. For example let us have two buttons in this component, one for error and one for success message.

customToastComp_Test.html
<template>
    <lightning-card title="Custom Show Toast" icon-name="custom:custom101">
        <c-custom-show-toast-message></c-custom-show-toast-message>
        <lightning-layout multiple-rows="true">
            <lightning-layout-item padding="around-small" size="8">
                <div class="page-section page-right">
                    <lightning-button variant="brand" label="Show Error Message" title="Show Error Message" onclick={handleErrorMsg} class="slds-m-left_x-small"></lightning-button>
                    <lightning-button variant="brand" label="Show Success Message" title="Show Success Message" onclick={handleSuccessMsg} class="slds-m-left_x-small"></lightning-button>
                </div>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

customToastComp_Test.js
import { LightningElement } from 'lwc';
export default class CustToastComponent_Test extends LightningElement {

    handleErrorMsg() {
        this.template.querySelector("c-custom-show-toast-message").showCustToastEvent({
            detail: {
                title: 'Error',
                message: 'This is a custom Error message.',
                variant: 'error',
                isAutoClose : true,
                duration: 10
            }
        });
    }

    handleSuccessMsg() {
        this.template.querySelector("c-custom-show-toast-message").showCustToastEvent({
            detail: {
                title: 'Success',
                message: 'This is a custom Success message.',
                variant: 'success',
                isAutoClose : false
            }
        });
    }
}

In the customToastComp_Test.js  we have two functions which are being called on button clicks.

The first function will call error message where we are passing 5 parameters.
  • title : The title of the Toast/Notification
  • message : Message to be displayed.
  • variant : variant of the toast , success/error.
  • isAutoClose : Boolean value- false if you do not want to automatically close the toast and the toast will not disappear until user clicks close. True if you want to automatically close the toast.
  • duration : Time in seconds for which the user wants to extends the display of the toast.
 handleErrorMsg() {
       this.template.querySelector("c-custom-show-toast-message").showCustToastEvent({
           detail: {
               title: 'Error',
               message: 'This is a custom Error message.',
               variant: 'error',
               autoClose: true,
               duration: 10
           }
       });
   }

In the second function we will call success message where we are passing only 4 parameters and isAutoClose as false to make the toast dismissible by user.

Demo:- Here you can see the Error Toast disappears automatically after 10 secs and Success Toast is manually closed.





Resources:
Salesforce Documents - LDS

Thank you all !
#Keep learning #Keep Sharing :)

Recent blogs:

Generic Modal Box in LWC
How to use hyperlink in custom Toast Notification message in LWC
Nested Accordion in LWC
Build custom add to favorites functionality using LWC









Comments

Popular posts from this blog

How to update Field Level Security in bulk ?

Assign Field Level Security(FLS) in Salesforce Demo:- In this blog we will see the easy way to update Field Level Security(FLS) for Permission sets/Profiles in bulk. I have created a tool to make the Admins job a little easier. Before jumping to tool let us see the different standard approach we follow to update FLS in Salesforce.                     As an admin we usually update FLS from salesforce setup/UI. If we are working on a new Application with many Permission sets and Objects with 100+ fields it can be very time consuming task. Using this tool we can assign FLS in just few mins. Let us take an example. Suppose we have a new application and we have created 20 Permission sets and 8 Profiles . Now there are 10 Objects in all and in each object we have 15 fields for which we need to update FLS for above Permission sets and Profiles. Let us first see the different approach to assign FLS in Salesforce. We have two ways in which we can update FLS for a particular field.  1 .To upd

How to create custom polymorphic field using LWC ?

How to create custom polymorphic field using LWC ? In this blog we will see how we can make polymorphic lookup field using LWC. What is Polymorphic field? A polymorphic field is one where related object might be one of the several different types of objects. There can be a use case where a customer wants to connect one object with multiple objects- i.e, relationships between objects or relate a child object to multiple parents's ojects. For example, in task Object we have three such polymorphic fields. The WhoId(Name) relationship of Task can be with Contact or a Lead. Assigned To field can be a User or a Queue. Similarly, a WhatId(Related To) relationship field of Task can be with many other objects like Accounts, Opportunities etc. In Salesforce, currently we do not have any OOTB option or may be we can say we do not have a datatype for polymorphic field which we can create but if required we can create a custom component to facilitate the same functionality. So let's get

How to use Hyperlink in Custom Toast Notification message using LWC

  Use Hyperlink in Custom Toast Notification message using LWC   We all know that a component can send a toast notification that pops up to alert users of a success, error, or warning. A toast can also simply provide information to the user. But what if we need a hyperlink on the message to navigate to the records on the message body. Yes, we can put Links as well on the message body as we can see in Standard Notification Toasts. This is very simple just we need to remember few things. We should know how to use Navigation Services by using NavigationMixin.GenerateUrl method. Let us see the functionality in this blog. To display a toast notification in Lightning Experience or Experience Builder sites we import ShowToastEvent from the lightning/platformShowToastEvent module. We use this ShowToastEvent to provide feedback to a user following an action, such as after a record is created. Now in this blog we will see how to add hyperlink in the message of the Show Toast event and navig