Home Salesforce Inheritance in Lightning Web Component

Inheritance in Lightning Web Component

by Dhanik Lal Sahni

Lightning Web Component is new Salesforce development framework which is based on current Web Standards. We can utilize all features of web standards in our lightning web component. In this blog we will cover one of requirement which is very basic for all lightning community.

Use Case / Requirement
We have requirement that, We need to show current user detail on Portal Header. This current user detail can be accessed by other component as well for referring current user information.

Solution
As we need to show user detail on other components, so we can create global module or class inheritance. Class Inheritance is important feature of ES6+.

Let us resolved this task as class inheritance.

  1. Create BaseElement component in your LWC Project.

    import { LightningElement,api } from 'lwc';
    
    export default class BaseElement extends LightningElement {
        @api
        get currentCustomerName() {
            return sessionStorage.getItem("name");
        }
    
        set currentCustomerName(value) {
            sessionStorage.setItem("name",value);
        }
    }
    

    We have used sessionStorage API of window class. This api is used to store information in session, so that value will be accessible in all component in current user session.

  2. Create DerivedElement component in your LWC Project.

    import { track } from 'lwc';
    import BaseElement from 'c/baseElement';
    export default class DerivedElement extends BaseElement {
        //currentCustomerName is declared in base Element
        @track customerName=this.currentCustomerName;
    }
    

    We have inherited derivedElement from BaseElement class. All methods and properties of baseElement will be accessible in derived elements.

You may also like

6 comments

Arvind Gautam April 23, 2019 - 1:30 pm

Very nice and concise article to implement this necessary requirement.
Thanks for your valuable efforts and looking forward for this kind of article in future as well.

Reply
Dhanik Lal Sahni April 23, 2019 - 1:33 pm

Thank You Arvind.

Reply
Kishan April 23, 2019 - 1:30 pm

such a beautiful post
it reduce our code
and give us more flexibility

Reply
Dhanik Lal Sahni April 23, 2019 - 1:33 pm

Thank You Kishan.

Reply
Dhanik Lal Sahni May 3, 2020 - 8:11 am

Thank You Abhishek. It is great that my blog is useful for ohana.

Reply

Leave a Comment