Posted in Salesforce

Salesforce Lightning Communities : Working Navigation with LWC Component

Lightning component uses forceCommunity:navigationMenuBase extension to create customized navigation for the community templates. It has v.menuItems variable that holds the menu items created in the navigation. But the equivalent extension is not available for the LWC component yet.

Still, if we decide to go with LWC, here is the way:

Since, the extension is not available, we can develop the LWC component utilizing the same variable, but by embedding inside an Aura component. Here is an example for the custom navigation component – Navigation.cmp

<aura:component access="global" 
    extends="forceCommunity:navigationMenuBase"
    implements="forceCommunity:availableForAllPageTypes">

    <aura:attribute name="menuItems" type="Object[]" />

    <!-- CALL LWC NAVIGATION COMPONENT -->
    <c:lwcNavigation menuItems="{!v.menuItems}" onnavigateto="{!c.handleNavigation}"/>

</aura:component>	

Now, in the lwcNavigation component created in LWC, we need to have an api variable menuItems. Also, we need an event that triggers back to the Aura Component – Navigation.cmp to trigger the navigation, since navigate method is still available only for aura.

Here is lwcNavigation.js:

import { LightningElement, api } from 'lwc';

export default class LwcNavigation extends LightningElement {
    @api menuItems;

    navigateToMenu(event) {
        this.dispatchEvent(new CustomEvent('navigateto', {
            detail: {
                menuItemId : event.target.dataset.menuId
            }
        }));
    }
}

navigateToMenu is the method that can be called from the menu item iterator in the LWC. Now, to capture the event in the Aura, use the following code snippet in NavigationController.js:

({
    handleNavigation: function (component, event) {
        var id = event.getParam("menuItemId");
        if (id) {
            component.getSuper().navigate(id);
        }
    }
})

Now, you need to add this Aura Component to the Community, not the LWC component.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s