LearnFrenzy
Sign in Take a free test

Datatables, Modals and Navigation · Lesson 20 of 25

LWC Modals, Toasts and Navigation

6 min read Updated Nov 8, 2026 Saurabh Samir

Three small platform services make components feel native to Salesforce: modals for focused tasks and confirmations, toasts for feedback after an action, and navigation to records, lists and pages without hard-coding URLs. Each has a modern, supported API – no more hand-built modal markup with z-index hacks.

In this lesson

  • Modals with LightningModal
  • Toasts with ShowToastEvent and lightning/toast
  • Navigation with NavigationMixin

A modal with LightningModal

A modal is its own component that extends LightningModal instead of LightningElement:

<!-- discountModal.html -->
<template>
    <lightning-modal-header label="Approve discount"></lightning-modal-header>
    <lightning-modal-body>
        <p>Approve a {percent}% discount on {dealName}?</p>
    </lightning-modal-body>
    <lightning-modal-footer>
        <lightning-button label="Cancel" onclick={handleCancel}></lightning-button>
        <lightning-button label="Approve" variant="brand" onclick={handleApprove}></lightning-button>
    </lightning-modal-footer>
</template>
// discountModal.js
import { api } from 'lwc';
import LightningModal from 'lightning/modal';

export default class DiscountModal extends LightningModal {
    @api dealName;                            // values passed to open()
    @api percent;

    handleCancel() {
        this.close('cancel');                 // close() returns a value to the opener
    }

    handleApprove() {
        this.close('approved');
    }
}
<!-- discountRequest.html -->
<template>
    <lightning-button label="Request 15% discount" onclick={openModal}></lightning-button>
    <p>{status}</p>
</template>
// discountRequest.js
import { LightningElement } from 'lwc';
import DiscountModal from 'c/discountModal';

export default class DiscountRequest extends LightningElement {
    status = 'No request yet';

    async openModal() {
        const result = await DiscountModal.open({
            size: 'small',                       // small | medium | large | full
            label: 'Approve discount',           // accessible name
            dealName: 'Acme renewal',            // @api properties of the modal
            percent: 15,
        });
        // result is whatever close() passed, or undefined if the user pressed Esc / X
        this.status = result === 'approved' ? 'Discount approved ✔' : 'Discount not approved';
    }
}

Result (the user clicks Approve in the modal)

[Request 15% discount]
No request yet

› click “Request 15% discount”
[Request 15% discount]
Discount approved ✔
modal opened: "Approve discount" size=small props={"dealName":"Acme renewal","percent":15}

Here's the modal component itself, mounted on its own:

// discountModal.js – same files as above

The modal's content

▌Approve discount
Approve a 15% discount on Acme renewal?
[Cancel] [Approve]

› click “Approve”
▌Approve discount
Approve a 15% discount on Acme renewal?
[Cancel] [Approve]
modal closed with "approved"
  • Modal.open({...}) returns a promise that resolves when the modal closes, with the value passed to this.close(value).
  • Every key except size, label and description is passed to the modal's @api properties.
  • Focus trapping, the backdrop, Esc to close and screen-reader announcements are handled for you. For a simple yes/no question, lightning/confirm and lightning/alert are even shorter.

Toasts

Two APIs exist. ShowToastEvent is the long-standing one that works on Lightning Experience pages; lightning/toast is newer and also works in Experience Cloud sites and other containers:

// noteSaver.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import Toast from 'lightning/toast';

export default class NoteSaver extends LightningElement {
    saveClassic() {
        this.dispatchEvent(new ShowToastEvent({
            title: 'Note saved',
            message: 'Your note was added to the account.',
            variant: 'success',                    // info | success | warning | error
        }));
    }

    saveModern() {
        Toast.show({ label: 'Note saved', message: 'Synced to all devices', variant: 'success' }, this);
    }
}
<!-- noteSaver.html -->
<template>
    <lightning-button label="Save (ShowToastEvent)" onclick={saveClassic}></lightning-button>
    <lightning-button label="Save (lightning/toast)" onclick={saveModern}></lightning-button>
</template>

Toasts requested

[Save (ShowToastEvent)] [Save (lightning/toast)]

› click “Save (ShowToastEvent)”
[Save (ShowToastEvent)] [Save (lightning/toast)]
toast (success): Note saved – Your note was added to the account.

› click “Save (lightning/toast)”
[Save (ShowToastEvent)] [Save (lightning/toast)]
toast (success): Note saved – Synced to all devices

Use error toasts with mode: 'sticky' for problems the user must read; short success toasts disappear on their own.

Never build Salesforce URLs by hand – they differ between Lightning Experience, the mobile app and Experience Cloud. Describe where to go with a page reference and let the platform build the URL:

<!-- accountLinks.html -->
<template>
    <lightning-button label="Open account" onclick={openAccount}></lightning-button>
    <lightning-button label="New contact" onclick={newContact}></lightning-button>
    <lightning-button label="All opportunities" onclick={opportunityList}></lightning-button>
</template>
// accountLinks.js
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class AccountLinks extends NavigationMixin(LightningElement) {
    @api recordId;

    openAccount() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: { recordId: this.recordId, objectApiName: 'Account', actionName: 'view' },
        });
    }

    newContact() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: { objectApiName: 'Contact', actionName: 'new' },
            state: { defaultFieldValues: `AccountId=${this.recordId}` },   // pre-fill the new record form
        });
    }

    opportunityList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: { objectApiName: 'Opportunity', actionName: 'list' },
            state: { filterName: 'Recent' },
        });
    }
}

Navigation requests

[Open account] [New contact] [All opportunities]

› click “Open account”
[Open account] [New contact] [All opportunities]
navigate: {"type":"standard__recordPage","attributes":{"recordId":"001XX000003DGb2","objectApiName":"Account","actionName":"view"}}

› click “New contact”
[Open account] [New contact] [All opportunities]
navigate: {"type":"standard__objectPage","attributes":{"objectApiName":"Contact","actionName":"new"},"state":{"defaultFieldValues":"AccountId=001XX000003DGb2"}}

› click “All opportunities”
[Open account] [New contact] [All opportunities]
navigate: {"type":"standard__objectPage","attributes":{"objectApiName":"Opportunity","actionName":"list"},"state":{"filterName":"Recent"}}
Page reference typeGoes to
standard__recordPagea record (view or edit)
standard__objectPagean object's home, list view or new-record form
standard__recordRelationshipPagea related list
standard__navItemPagea Lightning tab (custom app pages)
standard__webPagean external URL
comm__namedPagean Experience Cloud page

To render a real link (so users can open it in a new tab), generate the URL with this[NavigationMixin.GenerateUrl](pageRef) and put it in an <a href>.

Practice

Try it yourself

  1. Add a "Back to cases" button that navigates to the Case object's list view.

    Show solution
    <!-- backToCases.html -->
    <template>
        <lightning-button label="Back to cases" onclick={goBack}></lightning-button>
    </template>
    // backToCases.js
    import { LightningElement } from 'lwc';
    import { NavigationMixin } from 'lightning/navigation';
    
    export default class BackToCases extends NavigationMixin(LightningElement) {
        goBack() {
            this[NavigationMixin.Navigate]({
                type: 'standard__objectPage',
                attributes: { objectApiName: 'Case', actionName: 'list' },
            });
        }
    }

    Navigation request

    [Back to cases]
    
    › click “Back to cases”
    [Back to cases]
    navigate: {"type":"standard__objectPage","attributes":{"objectApiName":"Case","actionName":"list"}}

Quick check

What class does a modal component extend?

LightningModal from lightning/modal.

How does the opener get the user's choice from a modal?

await Modal.open(...) resolves with the value passed to this.close(value).

Why use NavigationMixin instead of a URL string?

URLs differ between containers (desktop, mobile, Experience Cloud); page references work everywhere.

Summary

  • Build modals by extending LightningModal; open() resolves with the close() value.
  • Show feedback with ShowToastEvent or lightning/toast.
  • Navigate with NavigationMixin page references; GenerateUrl for real links.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links