Sub topic 1
Showing a toast with ShowToastEvent
A toast is a short message that appears at the top of the page, stays for a moment, and then disappears. Lightning Web Components (LWC) use toasts to confirm a save, report an error, or warn about a problem without blocking the user. This chapter covers how a component raises a toast, what the event contains, and where it can fail.
Prerequisites
This chapter assumes you already know the following:
- The basic structure of a Lightning Web Component: an HTML template, a JavaScript class, and a metadata file.
- How to use
@apiand how to dispatch events withdispatchEvent. - Basic Salesforce concepts such as records, objects, and record IDs.
You do not need Promises or async/await for this chapter. They matter in later chapters, when a toast follows a save or a modal.
How a toast works
A component does not draw a toast itself. It asks the page to do it. The component dispatches a special event, ShowToastEvent. The container around your component (Lightning Experience, the Salesforce mobile app, or an Experience Cloud site) listens for that event and renders the toast.
This design has two consequences:
- Your component never holds a reference to the toast. You cannot update it or close it from code.
- The toast appears only if a container is listening. Outside such a container, the event is dispatched and nothing is shown.
Dispatching your first toast
The event class comes from the lightning/platformShowToastEvent module. Import it, create an instance with an options object, and pass the instance to this.dispatchEvent.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastDemo extends LightningElement {
handleSave() {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'The contact was saved.',
variant: 'success',
mode: 'dismissible'
})
);
}
}To try it, add a template with a button that calls handleSave:
<template>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>Expose the component on a Lightning page or in a utility bar, and click the button. A green toast with a check icon appears.
The options object
ShowToastEvent takes one argument, an object with these properties:
| Property | Type | Purpose |
|---|---|---|
| `title` | String | The bold heading of the toast. |
| `message` | String | The body text. It can contain placeholders such as `{0}`. |
| `messageData` | Array | Values that replace the placeholders in `message`. Covered in a later chapter. |
| `variant` | String | The visual style: `info`, `success`, `warning`, or `error`. |
| `mode` | String | How long the toast stays: `dismissible`, `pester`, or `sticky`. |
If you leave out variant, the toast uses info. If you leave out mode, it uses dismissible. The next chapter looks at variants and modes in detail. For now, remember that title is the one property you should almost always set, and that message adds the detail.
Choosing good text
The toast text is the only feedback many users read, so write it deliberately:
- Put the outcome in the title ("Saved", "Delete failed").
- Put the reason or next step in the message ("The contact was saved." or "Required field Last Name is missing.").
- Keep the message to one sentence. A toast disappears, so users cannot reread it.
- Do not put information in a toast that the user must keep. Use a sticky toast or a visible element on the page for that.
Reusing the dispatch code
Real components raise toasts in several places: after a save, after a failed call, and after validation. Repeating the new ShowToastEvent block each time is noisy. Put it in a small helper method on the class.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastHelperDemo extends LightningElement {
showToast(title, message, variant) {
this.dispatchEvent(
new ShowToastEvent({ title, message, variant })
);
}
handleSuccess() {
this.showToast('Success', 'The contact was saved.', 'success');
}
handleFailure() {
this.showToast('Error', 'The contact could not be saved.', 'error');
}
}Dispatch the event on this. Do not dispatch it on a child element or a custom node you created, because the container expects the event to bubble up from your component's host element.
If many components need the same helper, move it into a shared service module that takes the component as an argument and calls component.dispatchEvent(...). The event still has to be dispatched from a component, so the helper needs a reference to one.
Common errors and gotchas
- Wrong import path. The correct module is
lightning/platformShowToastEvent. Importing fromlightning/toastor a similar path fails at build time. - Forgetting
new.ShowToastEventis a class. Calling it withoutnewthrows an error. - Passing a non-string
message. If you pass an error object, the toast shows[object Object]. For errors from Apex or the Lightning Data Service, readerror.body.message. Fall back toerror.messagefor JavaScript errors. - Dispatching in a place with no listener. Toasts need a hosting page that handles the event. Components shown through Lightning Out, or in a plain page outside Salesforce, show nothing. The Salesforce mobile app and Experience Cloud sites have their own toast rendering, so check how it looks there before you release.
- Toasts from the
renderedCallback. A toast raised there appears every time the component rerenders. Raise toasts from handlers that respond to a user action or a completed operation. - Flooding the user. Dispatching a toast inside a loop shows many stacked toasts. Collect the results and show one summary.
Testing that a toast is raised
You can check a toast in Jest without a real page. The @salesforce/sfdx-lwc-jest package replaces lightning/platformShowToastEvent with a stub. The stub dispatches a normal CustomEvent named lightning__showtoast, and the options appear in event.detail. Listen for that event on the component's host element.
import { createElement } from 'lwc';
import ToastDemo from 'c/toastDemo';
describe('c-toast-demo', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows a success toast when Save is clicked', () => {
const element = createElement('c-toast-demo', { is: ToastDemo });
const handler = jest.fn();
element.addEventListener('lightning__showtoast', handler);
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
expect(handler).toHaveBeenCalledTimes(1);
const detail = handler.mock.calls[0][0].detail;
expect(detail.title).toBe('Success');
expect(detail.variant).toBe('success');
});
});Because the toast is just an event, this test checks exactly what your component is responsible for: raising the event with the right options. It does not check how the page draws the toast.
Summary of the pattern
- Import
ShowToastEventfromlightning/platformShowToastEvent. - Build it with
title, plusmessage,variant, andmodeas needed. - Dispatch it with
this.dispatchEvent(...)from a handler that runs after a user action or a completed operation. - Extract a helper when several handlers need the same pattern.
Exercise
A developer's save handler calls new ShowToastEvent({ title: 'Saved' }) but never calls this.dispatchEvent. No toast appears. Explain why, and say what variant and mode the toast would have if it were dispatched.
Show answer
Creating the event object only builds it. The page container shows a toast when it receives the event, so the component must pass it to this.dispatchEvent(...). If dispatched, the toast would use the defaults: info for variant and dismissible for mode.
Exercise
An Apex call fails and the catch block runs new ShowToastEvent({ title: 'Error', message: error, variant: 'error' }). The toast shows [object Object]. How do you fix the message?
Show answer
The message must be a string, and error is an object. Use the text inside it, for example error.body ? error.body.message : error.message. This reads the server message when it exists and falls back to the JavaScript error message.