February 27, 2020

Navigating to a Page in Lightning Community using Custom Lightning Component

Sample Code:

Component1 cmp:

  1. <aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >  
  2.       
  3.     <aura:attribute name="Txt" type="String" default=""/>  
  4.       
  5.     <div class="slds-box slds-theme_default">  
  6.           
  7.         This is component 1.<br/><br/>  
  8.         <lightning:input type="text" value="{!v.Txt}" label="Enter some text"/><br/>  
  9.         <lightning:navigation aura:id="navService"/>  
  10.         <lightning:button label="Navigate" onclick="{!c.navigateToComTwo}"/>  
  11.           
  12.     </div>  
  13.       
  14. </aura:component> 

Component1 JavaScript Controller:
  1. ({  
  2.       
  3.     navigateToComTwo : function(component, event, helper) {  
  4.           
  5.         event.preventDefault();  
  6.         var navService = component.find( "navService" );  
  7.         var pageReference = {  
  8.             type: "comm__namedPage",  
  9.             attributes: {  
  10.                 pageName: "sample"  
  11.             },  
  12.             state: {  
  13.                 sampleVar: component.get( "v.Txt" )  
  14.             }  
  15.         };  
  16.         sessionStorage.setItem('pageTransfer', JSON.stringify(pageReference.state));  
  17.         navService.navigate(pageReference);  
  18.           
  19.     }  
  20.       
  21. }) 


Component2 cmp:

  1. <aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >  
  2.       
  3.     <aura:attribute name="Text" type="String" default=""/>  
  4.       
  5.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
  6.       
  7.     <div class="slds-box slds-theme_default">  
  8.           
  9.         This is component two.<br/><br/>  
  10.         Text is {!v.Text}.<br/><br/>  
  11.           
  12.     </div>  
  13.       
  14. </aura:component> 


Component3 JavaScript Controller:

  1. ({  
  2.       
  3.     doInit : function( component, event, helper ) {  
  4.           
  5.         var resultMsg = sessionStorage.getItem( 'pageTransfer' );  
  6.         component.set( "v.Text", JSON.parse( resultMsg ).sampleVar );  
  7.           
  8.     }  
  9.       
  10. }) 

Output:



4 comments:

  1. This did not work when i tried in developer edition Community

    ReplyDelete
    Replies
    1. I tried the same in my developer edition. It worked. Make sure the Page name is correct.

      Delete
  2. Hi,
    I have requirement like moving from one lightning component to another lightning component in community ,how can we do this?

    ReplyDelete
    Replies
    1. This example is from Lightning community.
      One more way is to use a parent component with multiple components in it and use hide and show.

      Delete