Navigation from one LWC component to another LWC Component

How to navigate from one LWC Component to another LWC Component. Let's look at it.

It's such a bummer that we cannot navigate from one Lightning Web component to another Lightning Web Component.

However, there is a workaround, if you want to navigate the user from one LWC to another LWC, you can embed LWC in an Aura Component and navigate the user from LWC to an Aura Component.

Out of the box, LWC framework provides us helper methods to send the user from Lightning Web Component to an Aura Component.

In fact, there are a whole bunch of destinations to which we can navigate the user from a Lightning Web Component.

Let's look at the snippet to send a user from LWC to Aura Component (that has another LWC embedded in it).

<template>
    <lightning-button label="Send" onclick={handleNavigation}></lightning-button>
</tempplate>
navigationExample.html

This is the controller file of the Web Component.

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class NavigationExample extends NavigationMixin(LightningElement) {

handleNavigation() {
       this[NavigationMixin.Navigate]({
        type: 'standard__component',
        attributes: {
            componentName: 'c__MyLightningComponent'
        },
        state: {
            c__counter: '5'
        }
    });
   }
}    
navigationExample.js

This is how the configuration object is going to look like and pretty much all the info that we need to provide related to the navigation will be provided to this.

    {
        /* type will be standard__component if the destination
        * is an Aura Component.
        */
        type: 'standard__component',
        
        /* This is going to be the name of the Aura Component 
        * that we need to navigate the user to.
        */
        attributes: {
            componentName: 'c__MyLightningComponent'
        },
        
        /* If I need to pass some data to the destination
         * component, I need to provide it to the 
         * key "state" as an object. 
         */
        state: {
            c__counter: '5'
        }
    }
config object used in the controller.js

Just a heads up make sure you include the namespace before the key in the object that you provide for the key state.

This is the Aura Component in to which you need to embed the Lightning Web Component.

<!-- ParentAuraComponent.cmp -->
<aura:component>
    <c:navigation-example />
</aura:component>
ParentAuraComponent.cmp

Hope this was helpful!