Stay on same tab after page refresh lightning-tab lwc

Telegram logo Join our Telegram Channel
stay-on-same-tab-after-refresh-lwc


The Problem

There is a Lightning Application with a lightning tab set Lightning Web Component inside it. In that application when the page is refreshed the current tab is changed to the default tab and needs to manually select the previously selected tab after the page is refreshed.



Solution

We are going to use the URL parameter to track and set the current tab when the page is refreshed. Every time user changes the tab, we will update the URL parameter with the value of the newly selected tab, so when the page is refreshed from the browser, the user will stay on the same tab.



Code & Explaination

In the JS controller of the Lightning web component, I have defined one attribute with the name activeTab to hold the value of the currently selected tab.

To get the URL info and parameter I have wired CurrentPageReference method from Lightning Navigation API. Also, the value of the activeTab is set to the URL parameter c__activeTab.

To update the URL when a tab is changed, NavigationMixin.Navigate() is being called. I am passing here the current page reference clone with c__activeTab set to the currently selected tab value. So when the next time the page is refreshed, the user will return to the same tab.


stayOnSameTabDemo.js

import { LightningElement, wire } from "lwc";
import { CurrentPageReference, NavigationMixin } from "lightning/navigation";
export default class StayOnSameTabDemo extends NavigationMixin(
    LightningElement
) {
    activeTab = "Tree1";

    @wire(CurrentPageReference)
    setCurrentPageReference(currentPageReference) {
        this.currentPageReference = currentPageReference;

        if (currentPageReference.state) {
            this.activeTab = currentPageReference.state.c__activeTab;
            console.log("this.activeTab", this.activeTab);
        }
    }

    handleOnActive(event) {
        event.preventDefault();
        event.stopPropagation();
        if (this.activeTab !== event.target.value) {
            this.activeTab = event.target.value;

            this[NavigationMixin.Navigate](
                this.getUpdatedPageReference({
                    c__activeTab: this.activeTab
                }),
                true /* replace parameter is set to true so that browser 
                navigates to new page without pushing it into page history, 
                so user does not have click browser's back button multiple times. */
            );
        }
    }

    getUpdatedPageReference(stateChanges) {
        return Object.assign({}, this.currentPageReference, {
            state: Object.assign(
                {},
                this.currentPageReference.state,
                stateChanges
            )
        });
    }
}


In the HTML code, the active-tab-value attribute of lightning-tabset is set to the activeTab property of this component, so whenever the page reloads URL parameter value will be set to the active-tab-value.

stayOnSameTabDemo.html

<template>
    <div class="slds-theme_default">
        <lightning-tabset variant="standard" active-tab-value={activeTab}>
            <lightning-tab onactive={handleOnActive} label="Tab One" value="One">
                <div class="slds-var-p-horizontal_small">
                    <h1 class="slds-text-heading_large">You are on tab one</h1>
                </div>
            </lightning-tab>
            <lightning-tab onactive={handleOnActive} label="Tab Two" value="Two">
                <div class="slds-var-p-horizontal_small">
                    <h1 class="slds-text-heading_large">You are on tab two</h1>
                </div>
            </lightning-tab>
        </lightning-tabset>
    </div>
</template>

stayOnSameTabDemo.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>


Final Notes

This was a simple example with one tabset only but you have multiple tabsets in a nested structure that also can be tracked with multiple URL parameters. I hope this post has helped you.

Please share if you like this post. Thank you!


2 comments:
  1. Hello Rahul,
    Will these changes works for standard tabs as well like Details and Related tabs on Lightning record page. I have seen that URL wont change when we navigate to these tabs.

    ReplyDelete
    Replies
    1. Hi Dear Unknown, Unfortunately we can't capture the standard tab change event, so we can't do this with standard tabs.

      Delete

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com