Sub topic 2
Toast variants and modes
A toast is a short message that appears at the top of the page after something happens. The previous chapter showed how to dispatch a ShowToastEvent. This chapter covers two properties of that event: variant controls how the toast looks and what it means, and mode controls how long it stays and whether the user can close it.
This chapter assumes you can write a basic LWC (template, class, and metadata file). It also assumes you know how dispatchEvent works and have seen ShowToastEvent once.
The four variants
The variant property sets the color and icon of the toast. It accepts four values.
| Variant | Typical use | Appearance |
|---|---|---|
| `info` | Neutral news, such as "Sync started" | Gray, info icon |
| `success` | An operation finished correctly | Green, check icon |
| `warning` | The action worked, but the user should look at something | Yellow, warning icon |
| `error` | An operation failed | Red, error icon |
If you leave variant out, the toast uses info. A missing variant therefore makes a failure look neutral, so set it on every toast you dispatch.
Variants carry meaning for the user and should match what actually happened. Don't use success for something that only started (a queued job), and don't use error for a validation hint the user can fix on the spot.
The three modes
The mode property controls the toast's lifetime and whether it has a close button.
| Mode | Close button | Disappears |
|---|---|---|
| `dismissible` | Yes | When the user closes it, or automatically after about 3 seconds, whichever comes first |
| `pester` | No | Automatically after about 3 seconds |
| `sticky` | Yes | Only when the user closes it |
If you leave mode out, the toast uses dismissible.
The mode decides whether the user is guaranteed to read the message. A pester toast cannot be closed early, but it also cannot be read later if the user looked away. A sticky toast waits until the user acts on it.
Choosing a mode
A practical rule set:
- Use
dismissiblefor routine confirmations such as "Saved". This is the default and works for most cases. - Use
stickyfor errors and for toasts with a link, because the user needs time to read the text or click the link. - Use
pestersparingly. It fits brief notices that the user should see but should not have to dismiss, and it leaves no way to close the toast early.
A reusable helper
Most components show several kinds of toasts. Writing the full ShowToastEvent each time invites mistakes, such as a forgotten variant. A small helper method keeps the choices in one place.
The component below saves nothing. It simply shows each combination so you can try them in a scratch org.
<template>
<lightning-card title="Toast playground">
<div class="slds-var-p-around_medium">
<lightning-button label="Success" onclick={handleSuccess}></lightning-button>
<lightning-button label="Info" onclick={handleInfo}></lightning-button>
<lightning-button label="Warning" onclick={handleWarning}></lightning-button>
<lightning-button label="Error" onclick={handleError}></lightning-button>
</div>
</lightning-card>
</template>import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastPlayground extends LightningElement {
showToast(title, message, variant, mode) {
this.dispatchEvent(
new ShowToastEvent({
title,
message,
variant,
mode
})
);
}
handleSuccess() {
this.showToast('Saved', 'Your changes were saved.', 'success', 'dismissible');
}
handleInfo() {
this.showToast('Heads up', 'A sync is running in the background.', 'info', 'pester');
}
handleWarning() {
this.showToast('Check the amount', 'The amount is unusually high.', 'warning', 'dismissible');
}
handleError() {
this.showToast('Save failed', 'The server rejected the request.', 'error', 'sticky');
}
}<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>Add the component to an app page and click each button. You should see four toasts that differ in color and in how long they stay.
Reporting errors in a toast
Error toasts are where mode and message quality matter most. Errors from Apex and from the Lightning Data Service arrive in different shapes, and showing [object Object] to a user is a common mistake.
An error from an Apex call or a lightning/uiRecordApi function usually has a body with a message. A plain JavaScript error has a message directly. A helper can handle both:
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { deleteRecord } from 'lightning/uiRecordApi';
export default class SafeDelete extends LightningElement {
reduceError(error) {
if (error && error.body && typeof error.body.message === 'string') {
return error.body.message;
}
if (error && typeof error.message === 'string') {
return error.message;
}
return 'Unknown error';
}
async handleDelete(recordId) {
try {
await deleteRecord(recordId);
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: 'The record was deleted.',
variant: 'success'
})
);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: this.reduceError(error),
variant: 'error',
mode: 'sticky'
})
);
}
}
}The success toast omits mode, so it uses dismissible and clears itself. The error toast is sticky, so the user can read the server's message before it vanishes.
Common mistakes
- Omitting the variant. The toast defaults to
info, so a failure looks like a neutral notice. - Using
pesterfor errors. The user cannot close it, and it disappears after about 3 seconds. Usestickyfor anything the user must act on. - Stacking many sticky toasts. Each one stays until closed. A loop that dispatches a sticky toast per failed row can bury the page. Combine the results into one toast instead.
- Passing an invalid string. Values such as
'Success'with a capital letter or'danger'are not valid variants. Use the lowercase names in the table above. - Putting markup in the message. The message is plain text. Links need
messageData, which a later chapter covers.
Summary of the decisions
For each toast, make two choices. Pick the variant by outcome: success, info, warning, or error. Pick the mode by how much the user needs to read: dismissible for routine feedback, sticky for errors and links, and pester only for brief notices. The combined flow chapter at the end of this tutorial uses exactly this pairing, with a default toast for success and a sticky one for failure.
Exercise
A component saves a record. On success it should show a green toast that the user can close but that also clears itself. On failure it should show a red toast that stays until the user reads and closes it. Write the two ShowToastEvent constructors, including the variant and mode of each.
Show answer
Success: new ShowToastEvent({ title: 'Saved', message: 'The record was saved.', variant: 'success', mode: 'dismissible' }). Failure: new ShowToastEvent({ title: 'Save failed', message: errorMessage, variant: 'error', mode: 'sticky' }). The dismissible mode shows a close button and also disappears after about 3 seconds. The sticky mode shows a close button and never disappears on its own. The success mode could be omitted, since dismissible is the default.
Exercise
A teammate writes new ShowToastEvent({ title: 'Import failed', message: 'See the log.', mode: 'pester' }). Name two problems with it and fix them.
Show answer
First, no variant is set, so the toast defaults to info and looks neutral instead of showing a failure. Second, pester has no close button and clears after about 3 seconds, so the user may miss the message. Fix: add variant: 'error' and change the mode to sticky (or dismissible if the message is not critical).