0

I need to show toast message in separate lines using LWC. Like this, enter image description here

I tried with '\n' and 'br' tag but it is not working.

<div>
    <lightning-button label="Toast Msg" variant="brand-outline" onclick={handleToastMsg} style="margin-left: 10px;"></lightning-button>
</div>

handleToastMsg(){
    var value = 'First Message \n';
    value += 'Second Message';

    const evt = new ShowToastEvent({
        title: 'Toast Success',
        message: value,
        variant: 'success',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

can anyone know how to do this? Thanks in advance!

4

2 Answers 2

2

We need to override the CSS to show the toast message in separate lines.

  • First, you must create one static resource file as mentioned below for the CSS.
  • Static Resource(public):

toastCSS.css

.toastMessage {
        white-space: break-spaces !important;
}

enter image description here

  • After that use this static resource in your LWC component.

HTML:

<template>
        <div>
                <lightning-button label="Toast Msg" variant="brand-outline" onclick={handleToastMsg} style="margin-left: 10px;">
                </lightning-button>
        </div>
</template>

JS:

import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { loadStyle } from 'lightning/platformResourceLoader';
import customCSS from '@salesforce/resourceUrl/toastCSS';
export default class DataBinding extends LightningElement {
    
    @track isCSSLoaded = false;

    renderedCallback() {

        if (this.isCSSLoaded) return;
        this.isCSSLoaded = true;
        loadStyle(this, customCSS).then(() => {
            console.log('css loaded successfully');
        }).catch(error => {
            console.log('error to load css');
        });
    }


    handleToastMsg() {
        var msg = 'First Message\nSecond Message\nThird Message';

        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: msg,
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}

Output:

enter image description here

1
  • Thanks! it is working
    – Kamal
    Commented Jul 31, 2023 at 9:15
1

Inserting line breaks is not supported. Ideally, the message conveyed in toast is succinct enough to be captured in one or two sentences. If you are trying to display more information, perhaps another notification mechanism would be better suited for the task.

That being said, LDS design guidance suggests patterns to condense text in situations where you might be listing users, contacts, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .