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.
- 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.
- 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.
6 comments
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.
Thank You Arvind.
such a beautiful post
it reduce our code
and give us more flexibility
Thank You Kishan.
Thank You Abhishek. It is great that my blog is useful for ohana.
[…] Inheritance in LWC (article by Dhanik Lal Sahni): https://salesforcecodex.com/salesforce/inheritance-in-lightning-web-component/ […]