Sub topic 16
Built-in alert, confirm, and prompt modals
This chapter assumes you can build an LWC with a template, a JavaScript class, and a metadata file. It also assumes you know async/await and the custom LightningModal pattern from earlier chapters, where a class extends LightningModal, is opened with a static open() call, and returns a value through close().
Many modals only need to show a sentence, ask yes or no, or collect one line of text. For those cases Salesforce ships three ready-made modals, so you don't need a template, a class, or a metadata folder.
The three modules
Each module exposes a static open() method that returns a Promise. You import each one from its own module path.
| Module | Import | Purpose | Buttons |
|---|---|---|---|
| LightningAlert | `lightning/alert` | Show a message | OK |
| LightningConfirm | `lightning/confirm` | Ask for confirmation | OK and Cancel |
| LightningPrompt | `lightning/prompt` | Ask for one line of text | OK and Cancel, with a text input |
The Promise settles when the user dismisses the modal. Your code reads the result after the await.
| Modal | Resolved value |
|---|---|
| Alert | `undefined` after the user dismisses it |
| Confirm | `true` for OK, `false` for Cancel |
| Prompt | The entered string for OK, `null` for Cancel |
Options
All three accept an options object.
messageis the body text. It is plain text, so don't pass HTML.labelis the heading text, which assistive technology also reads. Always set it.themesets the color of the header. Typical values aredefault,shade,inverse,alt-inverse,success,info,warning,error, andoffline.variantapplies to confirm only.headeris the default, andheaderlesshides the header.defaultValueapplies to prompt only. It pre-fills the text input.
Check the component reference for your API version, because the option lists grow over time.
LightningAlert
Use an alert when the user must acknowledge something before continuing. A toast can be missed, but an alert blocks the page until the user clicks OK.
import { LightningElement } from 'lwc';
import LightningAlert from 'lightning/alert';
export default class AlertDemo extends LightningElement {
async handleShowAlert() {
await LightningAlert.open({
message: 'Your session will expire in five minutes.',
label: 'Session warning',
theme: 'warning'
});
// Code here runs after the user clicks OK.
}
}<template>
<lightning-button label="Show alert" onclick={handleShowAlert}></lightning-button>
</template>The component stays alive while the alert is open. The await only pauses handleShowAlert, and the rest of the page remains in memory.
LightningConfirm
A confirm modal replaces the custom ConfirmDeleteModal from the earlier delete flow. It needs no extra component, because the result is a boolean.
import { LightningElement, api } from 'lwc';
import LightningConfirm from 'lightning/confirm';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { deleteRecord } from 'lightning/uiRecordApi';
export default class ConfirmDemo extends LightningElement {
@api recordId;
async handleDelete() {
const confirmed = await LightningConfirm.open({
message: 'Delete this record? This cannot be undone.',
label: 'Confirm delete',
theme: 'warning'
});
if (!confirmed) {
return;
}
try {
await deleteRecord(this.recordId);
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: 'The record was deleted.',
variant: 'success'
})
);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: error.body ? error.body.message : error.message,
variant: 'error',
mode: 'sticky'
})
);
}
}
}The check if (!confirmed) handles every path except OK. This is safer than comparing to false, because it also covers any unexpected falsy value.
LightningPrompt
A prompt asks for a single string. Use it for quick input such as a rename or a short reason.
import { LightningElement } from 'lwc';
import LightningPrompt from 'lightning/prompt';
export default class PromptDemo extends LightningElement {
async handleRename() {
const newName = await LightningPrompt.open({
message: 'Enter a new name for the report.',
label: 'Rename report',
defaultValue: 'Q4 Pipeline'
});
if (newName === null) {
return; // The user cancelled.
}
const trimmed = newName.trim();
if (trimmed === '') {
return; // The user clicked OK with an empty field.
}
// Use trimmed here.
}
}Handle both a cancel and an empty string. A user can click OK with the input cleared, and the result is then '', which is not null.
Choosing between built-in and custom modals
The built-in modals trade flexibility for speed.
- Use a built-in modal when one message, one yes/no answer, or one text value is enough.
- Use a custom
LightningModalwhen you need several fields, validation before closing, a record form, or events sent to the opener while the modal stays open. - A prompt gives you no validation hook. You can only check the value after the modal has closed, and then you must reopen it if the value is bad. If you need inline validation, build a custom modal.
Common errors
- Forgetting
await. Without it you get a pending Promise, which is truthy.if (LightningConfirm.open(...))always passes, so the delete runs without asking. Alwaysawaitthe call or use.then(). - Passing HTML in
message. The text renders literally. Keep it plain. - Omitting
label. The modal has no useful accessible name. Set it every time. - Treating the alert result as meaningful. The alert only tells you the user dismissed it.
- Calling
open()fromconnectedCallbackautomatically. A modal that appears on page load, with no user action, is disorienting. Open modals in response to a click or a clear state change. - Testing without a stub. Jest cannot render these modules unless your test setup provides stubs, so check that your Jest configuration resolves
lightning/alert,lightning/confirm, andlightning/prompt. If it doesn't, map them to a mock injest.config.js.
Exercise
A component calls const answer = await LightningPrompt.open({ message: 'Reason?', label: 'Reason' });. The user clears the input and clicks OK. What is answer, and how should the code distinguish this from the user clicking Cancel?
Show answer
answer is an empty string (''). Cancel resolves with null. Check answer === null for a cancel, and then check answer.trim() === '' for an empty entry before using the value.
Exercise
Why is if (LightningConfirm.open({ message: 'Delete?', label: 'Confirm' })) { deleteRecord(id); } a bug, and how do you fix it?
Show answer
open() returns a Promise, and a Promise object is always truthy, so the delete runs immediately without waiting for the user. Make the handler async, write const confirmed = await LightningConfirm.open({ ... });, and delete only when confirmed is true.