Reusable LWC component

How to use Service Component(Reusable component) in LIGHTNING WEB COMPONENT

LWC

This blog will help, How to create a Service Component in LWC and how to reuse in multiple places.

How to create a service component:-

this is similar as Lightning Web Component. First we need to create a LWC component and put naming (commonLib). this name is indicating , it’s a common Library component that’s can be use in different components

here we don’t need to write any code in HTML file. only use JS file

This blog cover common methods by commonLib Service component

  • Toast Message
  • Validation
  • DOB
  • Logo

commonLib.js

import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import LOGO from '@salesforce/resourceUrl/APXTConga4__ComposerLogoRed';

const LOGO_URL = ()  => {
    return LOGO;
}

const showMessage = (page,t,m,type) =>  {
     const toastEvt = new ShowToastEvent({
        title: t,
        message:m,
        variant: type
     })
     page.dispatchEvent(toastEvt);
}

const isValidForm = (elements) => {
    var isFormValid=true;
    const allValid = elements.reduce((validSoFar, inputCmp) => {
                inputCmp.reportValidity();
                return validSoFar && inputCmp.checkValidity();
    }, true);
    if (!allValid) {
        isFormValid=false;
    }
    return isFormValid;
}

const validateEmail=(email)=> {
    const regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

const validateDOB=(dob)=>{
    let dateOfBirth = new Date(dob);
    let today = new Date();
    if(dateOfBirth<today){
       return true;
    }
       return false;
   }

export{
    showMessage,
    isValidForm,
    LOGO_URL,
    validateEmail,
    validateDOB
}

demoLWC.html

<template>
    <lightning-card class="slds-m-around_medium" title="Create New Contact" id="vendor-form">
        <span style="display: inline-block;"><img src={imgURL}></span>  
        <div style="margin-left : 10px;margin-right: 10px;" >
        <div>
            <p class="slds-text-body_regular">Please confirm information below to register.</p>
        </div>
        <div class="slds-page-header">
            Contact Information <span style="color:red">(All Fields Required)</span>
        </div>
        <div class="c-container">
            <div class="slds-grid slds-gutters">
                <div class="slds-col slds-grid slds-size_1-of-1 slds-large-size_6-of-12">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_none">

                        <div class="slds-form-element">
                            <lightning-combobox name="title" label="Title" value="" placeholder="Select an Option" options={options} required>
                            </lightning-combobox>
                        </div>
                    </div>
                </div>
            </div>
            <div class="slds-grid slds-gutters">
                <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12">

                    <div class="slds-form-element">

                        <lightning-input type="text" name="firstName" label="First Name" required></lightning-input>

                    </div>

                    <div class="slds-form-element">
                        <lightning-input required type="text" name="lastName" label="Last Name"></lightning-input>

                    </div>
                    <div class="slds-form-element">
                        <span>
                            <lightning-formatted-text class="slds-form-element__label slds-no-flex" value="Primary Phone#" name="primaryPhone"></lightning-formatted-text>
                        </span>
                        <lightning-layout multiple-rows="true">
                            <lightning-layout-item padding="horizontal-small" size="4" flexibility="auto">
                                <lightning-input required type="tel" name="phone1" label="" maxlength="3" pattern="\d{3}" message-when-pattern-mismatch="Please enter only digits" ></lightning-input>
                            </lightning-layout-item>
                            <lightning-layout-item padding="horizontal-small" size="4" flexibility="auto">
                                <lightning-input required type="tel" name="phone2" label="" maxlength="3" pattern="\d{3}" message-when-pattern-mismatch="Please enter only digits"></lightning-input>
                            </lightning-layout-item>
                            <lightning-layout-item padding="horizontal-small" size="4" flexibility="auto">
                                <lightning-input required type="tel" name="phone3" label="" maxlength="4" pattern="\d{4}" message-when-pattern-mismatch="Please enter only digits"></lightning-input>
                            </lightning-layout-item>
                        </lightning-layout>

                    </div>

                </div>
                <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12">
                    <p></p>
                    <div class="slds-form-element">
                        <lightning-input type="email" name="email" label="Email" required></lightning-input>

                    </div>
                    <div class="slds-form-element">
                        <lightning-input required type="date" name="dob" label="Date of Birth"></lightning-input>

                    </div>
                </div>
            </div>
        </div>
        <lightning-layout multiple-rows="true">
            <lightning-layout-item padding="around-small" size="12" small-device-size="12" large-device-size="6" medium-device-size="6">
                <div class="slds-float_right">
                    <lightning-button label="Cancel" title="Cancel" onclick={handleCancel} class="slds-m-left_x-small"></lightning-button>
                    <lightning-button variant="brand" label="Create Contact" title="Brand action" onclick={handleSave} class="slds-m-left_x-small"></lightning-button>
                </div>
            </lightning-layout-item>
        </lightning-layout>
    </div>
    </lightning-card>
</template>

demoLWC.js

import { LightningElement } from 'lwc';
import { showMessage, LOGO_URL, isValidForm, validateEmail,validateDOB} from 'c/commonLib';


export default class DemoLWC extends LightningElement {
 
    get options(){
        return[
            { label: 'Dr.', value: 'dr.' },
            { label: 'Mr.', value: 'mr' },
            { label: 'Mrs.', value: 'mrs.' },
            { label: 'Ms.', value: 'ms.' }
        ]
    }
  
     imgURL = LOGO_URL;

   
    validatePage()
    {
        const elements = Array.from(
            this.template.querySelectorAll('lightning-input,lightning-input-field,lightning-combobox')
        );

        console.log('elements=> '+this.template.querySelectorAll('lightning-input,lightning-input-field,lightning-combobox'));
        return isValidForm(elements);
    }
    
    handleSave() {
        var message="";
        let isValid=true;
        let mandateCheck = this.validatePage();
        
        if(!mandateCheck){
            isValid = false;
            message = message + 'Please provide the required information to proceed with the registration.';
        }
        if(mandateCheck && !validateEmail(this.email)){
            isValid = false;
            message = message + '\n Please provide the valid email id.';
        }
        if(mandateCheck && !validateDOB(this.dob)){
            isValid = false;
            message = message + '\n Date of birth should not be in future.';  
        }
        if(!isValid)
        {
            showMessage(this,'Notification',message,'error');  
        }
    }

}

demoLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
     <targetConfig targets="lightning__RecordAction">
      <actionType>ScreenAction</actionType>
     </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

uniquesymbol

Leave a Reply