Sub topic 3
Adding a link to a toast message
This chapter assumes you can already dispatch a ShowToastEvent with a title, message, and variant. It also assumes you know basic LWC structure and how @api properties work. Here you add a clickable link to the toast text.
How messageData works
The message property of a toast is plain text. To put a link inside it, you add placeholders such as {0} and {1} to the message. Then you supply a messageData array. The toast replaces each placeholder with the item at the same index.
- A string item is inserted as plain text.
- An object with
urlandlabelproperties becomes a link. Thelabelis the visible text, andurlis where the link goes.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastWithLink extends LightningElement {
@api recordId;
showCreated(name) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Record created',
message: '{0} was created. {1}',
messageData: [
name,
{
url: '/lightning/r/Account/' + this.recordId + '/view',
label: 'Open it'
}
],
variant: 'success',
mode: 'sticky'
})
);
}
}In this example, {0} becomes the value of name. {1} becomes a link that reads "Open it" and points to the Account record page.
Why the example uses sticky mode
A toast with a link needs time to be clicked. In the default dismissible mode, the toast closes after a few seconds, and the user may miss the link. The sticky mode keeps the toast open until the user closes it. Use sticky when the link matters.
Choosing the URL
The url value is a string. In the example it is built by hand from a known Lightning path. This works, but it ties your code to a specific URL format. The chapter on generating URLs shows how NavigationMixin.GenerateUrl produces a correct URL from a page reference. That approach is more reliable than concatenating strings. Because GenerateUrl returns a Promise, you would wait for it to resolve before you dispatch the toast.
Common errors
- Placeholders without data. If the message contains
{1}butmessageDatahas only one item, the placeholder is not replaced as you expect. Make sure each placeholder has a matching item. - Putting a URL in
messagedirectly. The toast does not turn a bare URL into a link. Use a placeholder and an object withurlandlabel. - Missing label. An object without
labelgives the user nothing to click. Always set both properties. - Using a short-lived mode. A link in a
dismissibletoast may vanish before the user acts.
Exercise
A toast uses the message 'Saved {0}. {1}' and the messageData array [recordName, { url: someUrl, label: 'View' }]. What does the user see, and which mode is a good choice if you want them to have time to click the link?
Show answer
The user sees "Saved", then the value of recordName, then a link labeled "View" that opens someUrl. Placeholder {0} gets the string and {1} gets the object, which becomes a link. Use sticky mode so the toast stays until the user closes it.