LWC Navigation Scenarios with Examples

A lot of good many LWC Navigation examples and documentation are available scattered across different sources , so we thought of aggregating and providing it all here covering most of the navigation use cases.

To navigate in Lightning Experience, Lightning communities, and the Salesforce app, use the navigation service, lightning/navigation to navigate to many different page types, like records, list views, custom tabs, and objects and even open files.

Instead of a URL, the navigation service uses a PageReference. A PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page. Using a PageReference insulates your component from future changes to URL formats. It also allows your component to be used in multiple applications, each of which can use different URL formats.

NOTE – The type (String) and attributes (Object) are required parameters in all cases.
state (Object) is an optional parameter.

Let’s jump into the code

To use the Navigation Service in your LWC , import it in your JS file-

import { NavigationMixin } from 'lightning/navigation';

And apply the NavigationMixin function to your Component’s base class –

export default class My_lwc extends NavigationMixin(LightningElement) {
}

The NavigationMixin adds two APIs to your component’s class. Since these APIs are methods on the class, they must be invoked with this reference.

  • [NavigationMixin.Navigate](pageReference, [replace]): A component calls this[NavigationMixin.Navigate] to navigate to another page in the application.
  • [NavigationMixin.GenerateUrl](pageReference): A component calls this[NavigationMixin.GenerateUrl] to get a promise that resolves to the resulting URL. The component can use the URL in the href attribute of an anchor. It can also use the URL to open a new window using the window.open(url) browser API.

Navigation Service Examples

  1. RECORD PAGES :
// Navigate to View Account Record Page
    navigateToViewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.yourRecordId,
                objectApiName: 'Account',
                actionName: 'view'
            },
        });
    }
// Navigate to Edit Account Record Page
    navigateToEditAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.yourRecordId,
                objectApiName: 'Account',
                actionName: 'edit'
            },
        });
    }
// Navigate to Clone Account Record Page
    navigateToCloneAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.yourRecordId,
                objectApiName: 'Account',
                actionName: 'clone'
            },
        });
    }
//Communities don’t support the actionName values clone or edit.

2. OBJECT PAGES

// Navigate to New Account Page
navigateToNewAccountPage() {
    this[NavigationMixin.Navigate]({
        type: "standard__objectPage",
        attributes: {
            objectApiName: "Account",
            actionName: "new"
        },
    });
}

// Navigation to Account List view(recent)
navigateToAccountRecentListView() {
    this[NavigationMixin.Navigate]({
        type: "standard__objectPage",
        attributes: {
            objectApiName: "Account",
            actionName: "list"
        },
        state: {
            filterName: "Recent"
        },
    });
}
//filterName =  StringID or developer name of object"s list view.


// Navigate to a New Account page with default field values:
//    Name: Salesforce,
//    OwnerId: 005XXXXXXXXXXXXXXX,
//    AccountNumber: ACXXXX,
//    NumberOfEmployees: 35000
navigateToAccountDefault() {
    this[NavigationMixin.Navigate]({
        type: “standard__objectPage”,
        attributes: {
            objectApiName: "Account",
            actionName: "new"
        },
        state: {
            defaultFieldValues = "AccountNumber=ACXXXX,Name=Salesforce,NumberOfEmployees=35000,OwnerId=005XXXXXXXXXXXXXXX",
            nooverride: "1"
        }
    });
}


// Navigation to Case object home page
navigateToCaseHome() {
    this[NavigationMixin.Navigate]({
        type: "standard__objectPage",
        attributes: {
            objectApiName: "Case",
            actionName: "home"
        }
    });
}


//Navigate to Reports Standard Tab
navigateToReports() {
    this[NavigationMixin.Navigate]({
        type: "standard__objectPage",
        attributes: {
            objectApiName: "Report",
            actionName: "home"
        },
    });
}
//Navigate to Files Home/Standard tab
navigateToFilesHome() {
    this[NavigationMixin.Navigate]({
        type: "standard__objectPage",
        attributes: {
            objectApiName: "ContentDocument",
            actionName: "home"
        },
    });
}
//In communities, actionName = list and home are the same.
//In managed package, prefix the custom object with ns__

3. RECORD RELATIONSHIP PAGE
A page that interacts with a relationship on a particular record in the org. Only related lists are supported.

// Navigation to Contact related list of Account
    navigateToContactRelatedList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                relationshipApiName: 'Contacts',
                actionName: 'view'
            },
        });
    }
//actionName = Only view is supported.
//relationshipApiName = The API name of the object’s relationship field.

4. APP PAGES

//Navigate to a Standard App
navigateToSalesApp() {
    this[NavigationMixin.Navigate]({
        type: 'standard__app',
        attributes: {
            appTarget: 'standard__Sales',
        }
    });
}

//Navigate to a Custom App
navigateToMyCustomApp() {
    this[NavigationMixin.Navigate]({
        type: 'standard__app',
        attributes: {
            appTarget: 'c__MyCustomApp',
        }
    });
}
// Pass either the appId or appDeveloperName to the
// appTarget. The appId is the DurableId field on the AppDefinition object.
// For standard apps, the namespace is standard__. For custom
// apps, it’s c__. For managed packages, it’s the namespace
// registered for the package.

//Navigate to App Record Page in an App
navigateToAppRecordPage() {
    this[NavigationMixin.Navigate]({
        type: 'standard__app',
        attributes: {
            appTarget: 'standard__LightningSales',
            pageRef: {
                type: 'standard__recordPage',
                attributes: {
                    recordId: '001xx000003DGg0XXX',
                    objectApiName: 'Account',
                    actionName: 'view'
                }
            }
        }
    });
}

5. LIGHTNING COMPONENT PAGES :

To make an addressable LWC, embed it in an Aura component that implements the lightning:isUrlAddressable interface.

// Navigate to Lightning Component with Params
navigateToLC() {
    this[NavigationMixin.Navigate]({
        type: "standard__component",
        attributes: {
            //Here myCustomAura is name of Aura component
            //which implements lightning:isUrlAddressable
            componentName: "c__myCustomAura"
        },
        state: {
            c__counter: '5',
            c__recId: 'XXXXXXXXXXXXXXXXXX'
        }
    });
}
//You can pass any key and value in the state object. The key
//must include a namespace, and the value must be a string.

In Aura component, retrieve the sent params using component.get in the init controller method –

component.get("v.pageReference").state.c__counter);
component.get("v.pageReference").state.c__recId);

Retrieval of params in LWC is described in a detailed section below.

6. CUSTOM TABS :

navItemPage – A page that displays the content mapped to a custom tab. Visualforce tabs, Web tabs, Lightning Pages, and Lightning Component tabs are supported.

// Navigate to Custom Tab - VF tabs, Web tabs, Lightning Pages, and Lightning Component Tabs
navigateToTab() {
    this[NavigationMixin.Navigate]({
        type: 'standard__navItemPage',
        attributes: {
            apiName: 'MyCustomTabAPIName'
        },
        state: {
            c__counter: '5',
            c__recId: this.recId
        }
    });
}

7. WEB PAGES

// Navigate to an External URL
navigateToWebPage() {
    this[NavigationMixin.Navigate]({
        type: 'standard__webPage',
        attributes: {
            url: 'http://salesforce.com'
        }
    });
}
//Navigate to a Visualforce page
    navigateToVF() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url: '/apex/myVFPage?id=' + this.recId
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }
// Here we use NavigationMixin.GenerateUrl to form the URL and then navigate to it in the promise.

8. KNOWLEDGE ARTICLE :

// Navigate to Knowledge Article record
navigateToKnowledgeArticle() {
    this[NavigationMixin.Navigate]({
        type: 'standard__knowledgeArticlePage',
        attributes: {
            articleType: 'MyArticleType',
            urlName: 'Mar-2020'
        }
    });
}
//The articleType is API name of the Knowledge Article record.
//The urlName is the article's URL.

9. NAMED PAGES (standard) & FILE PREVIEW

// Navigate to Named Pages - A standard page with a unique name.
navigateToNamedPage() {
    this[NavigationMixin.Navigate]({
        type: 'standard__namedPage',
        attributes: {
            pageName: 'home'
        }
    });
}
// pageName possible Values - home , chatter, today, dataAssessment, filePreview


// Navigate to filePreview Page
navigateToFilePreview() {
    this[NavigationMixin.Navigate]({
        type: "standard__namedPage",
        attributes: {
            pageName: "filePreview"
        },
        state: {
            // assigning single ContentDocumentId
            selectedRecordId: this.id
        }
    });
}
// recordIds: '069xx0000000005AAA,069xx000000000BAAQ',
// selectedRecordId:'069xx0000000005AAA'

10. NAMED PAGES & LOGIN PAGE (community)

// Navigate to standard page used in Lightning communities
navigateToCommPage() {
    this[NavigationMixin.Navigate]({
        type: 'comm__namedPage',
        attributes: {
            name: 'Home'
        }
    });
}
// Supported pages in communities - Home, Account Management, Contact Support,
// Error, Login, My Account, Top Articles, Topic Catalog, Custom page

// Navigate to Authentication page in Lightning communities
navigateToLoginPage() {
    this[NavigationMixin.Navigate]({
        type: 'comm__loginPage',
        attributes: {
            actionName: 'login'
        }
    });
}
// Supported actionName = login, logout

Now that we have seen what all kinds of Navigation scenarios are provided, let’s also look at another feature, which is the URL generation done by NavigationMixin.GenerateUrl , as shown below-

recordPageUrl; // variable to be associated to anchor tag.

// Generate a URL to a User record page
generateURLforLink() {
    this[NavigationMixin.GenerateUrl]({
        type: 'standard__recordPage',
        attributes: {
            recordId: '005B0000001ptf1XXX',
            actionName: 'view',
        },
    }).then(generatedUrl => {
        this.recordPageUrl = generatedUrl;
    });
}
// NavigationMixin.GenerateUrl returns the Generated URL in the promise.
// We can even use this in  window.open(generatedUrl) command


Retrieving Params in LWC

We use CurrentPageReference to get a reference to the current page in Salesforce. Page URL formats can change in future releases. Hence, to future proof your apps, use page references instead of URLs.

import { CurrentPageReference } from 'lightning/navigation';
@wire(CurrentPageReference)
pageRef;

The key-value pairs of the PageReference state property are serialized to URL query parameters. 

Example of an LWC encoding defaultFieldValues in state and then navigating to another LWC and decoding them –

// navSenderLWC.js
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

export default class navSenderLWC extends NavigationMixin(LightningElement) {

    navigateWithParams() {
        const encodedValues = encodeDefaultFieldValues({
            FirstName: 'Waseem',
            LastName: 'Sabeel'
        });

        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Contact',
                actionName: 'new'
            },
            state: {
                defaultFieldValues: encodedValues
            }
        });
    }
}

And we use the Wired PageReference on the navigated LWC, and decode the field values as below –

// navReceiverLWC.js
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import { decodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

export default class navReceiverLWC extends LightningElement {

    @wire(CurrentPageReference)
    setCurrentPageRef(pageRef) {
        if (pageRef.state.defaultFieldValues) {
            const decodedValues = decodeDefaultFieldValues(pageRef.state.defaultFieldValues);
        }
    }
}

Note – All encoded default field values in the state are passed as strings.

So that was all about Lightning Navigation Scenarios and Examples.

A Note on Limitations –

The lightning/navigation service is supported only in Lightning Experience, Lightning communities, and the Salesforce app. It isn’t supported in other containers, such as Lightning Components for Visualforce, or Lightning Out. This is true even if you access these containers inside Lightning Experience or the Salesforce app.

For more detailed information , kindly refer to the Official Documentation provided here –

  1. All PageReference Types with attribute details
  2. Developer Guide
  3. lightning-navigation Component reference

Thank You!

Yours Wisely,
Waseem

2 thoughts on “LWC Navigation Scenarios with Examples

  1. Hi! How to navigate to Lightning Lead convert page that opens in a modal (to mimic standard convert lead behavior)? The below opens the convert page in the same tab but not in a modal.
    handleLeadConvert(){
    this[NavigationMixin.Navigate]({
    type: ‘standard__component’,
    attributes: {
    componentName: ‘runtime_sales_lead__convertDesktopConsole’
    },
    state: {
    leadConvert__leadId: this.recordId
    }});
    }

    Like

Leave a comment