Navigate from Lightning Web Component to another LWC or AURA component Salesforce | LWC Stack ☁️⚡️


 In this blog I will share two ways to navigate from a Lightning Web Component to another Lightning Web Component.

Navigate to AURA Component - In this method we will embed our Lightning Web Component in an AURA component. We will use aura because for redirection we will be using isUrlAddressable which is available in aura only. So technically it's more over like redirecting to an Aura component which is embedding LWC inside it.

Navigate to LWC - In this method we will use the one.app url to redirect to the target LWC. We will convert the component definition to a base64 encoded string first then we will pass the data in the url itself. 

In this demo I will create 3 components - 
1. navigateFromLWC - The source component from which we will be redirecting to another LWC component.
2. navigateToLWC - The target component to which we will make the redirection.
3. navigateToLWCAura - Aura component which will embed navigateToLWC.

Please check the example below : 

navigateFromLWC.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<template>
  <div class="slds-box">
    <lightning-button
      label="Navigate without AURA"
      onclick={navigateWithoutAura}
    ></lightning-button>
    <br />
    <br />
    <lightning-button
      label="Navigate with AURA"
      onclick={navigateWithAura}
    ></lightning-button>
  </div>
</template>

navigateFromLWC.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { LightningElement } from "lwc";
import { NavigationMixin } from "lightning/navigation";

export default class NavigateFromLWC extends NavigationMixin(LightningElement) {
  navigateWithAura() {
    this[NavigationMixin.Navigate]({
      type: "standard__component",
      attributes: {
        componentName: "c__navigateToLWCAura"
      }
    });
  }
  navigateWithoutAura() {
    let cmpDef = {
      componentDef: "c:navigateToLWC"
    };

    let encodedDef = btoa(JSON.stringify(cmpDef));
    this[NavigationMixin.Navigate]({
      type: "standard__webPage",
      attributes: {
        url: "/one/one.app#" + encodedDef
      }
    });
  }
}

navigateToLWC.html
1
2
3
4
5
<template>
  <div class="slds-box">
    <b>I am the target!</b>
  </div>
</template>

navigateToLWCAura.cmp
1
2
3
<aura:component implements="lightning:isUrlAddressable">
  <c:navigateToLWC></c:navigateToLWC>
</aura:component>

Output


Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments