Share JavaScript code across LWC components | LWC EMI Calculator

Telegram logo Join our Telegram Channel

In this post, we will see how to share reusable JS code into multiple Lightning web components. To avoid redundancy and add consistency to your codebase. I will demonstrate with a real-time example of the EMI Calculator given in the next section.

Share JavaScript code across LWC components | LWC EMI Calculator


Use Case

The business users at ABC Finance want a simple EMI calculator inside Salesforce so that they can calculate EMI on the go. 

To fulfill this requirement we will create a simple EMI Calculator using the Lightning Web Components framework. With the help of that example, I will explain how to share a reusable JavaScript Utility Component.

I have created a separate JS Utility component to store all EMI-related calculation functions so we can share them across different components in the org.


Follow the below steps to create a JS utility Lightning web component.

  1. Create a new Lightning web component with the name emiUtility. You can name your component as per the scenario
  2. Delete the .html file from the newly created component by going to the files explorer from your IDE, I am using VS code here. This is what my emiUtility component looks like:
    EMI Utility LWC

  3. Now, go to the .js file of your new utility component and delete all existing code.
  4. Write the functions or variables that you want to share and export all the items that you want to be made available for reuse. Here is the complete code in the emiUtility.js file:

    emiUtility.js
    function emiCalculator(principal, interest, tenure) {
        let rate = interest / (12 * 100);
        let ans =
            (principal * (rate * Math.pow(1 + rate, tenure))) /
            (Math.pow(1 + rate, tenure) - 1);
        return ans;
    }
    
    function yearToMonths(year) {
        return year * 12;
    }
    
    function monthsToYear(months) {
        return parseInt(months / 12, 10);
    }
    export { emiCalculator, yearToMonths, monthsToYear };
    

  5. Well done! Now deploy the emiUtility component to your org.
  6. Now it's time to use the emiUtility component. Go to the target component where you want to utilize the shared code from the emiUtility component. I have created a new component for the demo called emiCalculator.
  7. Import the items from the emiUtility component to use them in the .js file of the target component.
  8. Call the functions wherever needed. This is what the complete code looks like after importing our emiUtility component.

    emiCalculator.js
    import { LightningElement } from "lwc";
    
    import { emiCalculator, yearToMonths, monthsToYear } from "c/emiUtility";
    export default class EmiCalculator extends LightningElement {
        principal = 100000;
        interest = 10;
        tenure = 120;
        emi = 0;
        tenureInMonths = true;
    
        connectedCallback() {
            this.calculate();
        }
    
        handleChange(event) {
            this[event.target.name] = event.target.value;
            this.calculate();
        }
    
        handleMonthToggle(event) {
            this.tenureInMonths = event.target.checked;
            if (this.tenureInMonths) {
                // convert to months
                this.tenure = yearToMonths(this.tenure);
                console.log("converted to months", this.tenure);
            } else {
                // already in months so convert to years
                this.tenure = monthsToYear(this.tenure);
                console.log("converted to years", this.tenure);
            }
            this.calculate();
        }
    
        calculate() {
            this.emi = emiCalculator(
                this.principal,
                this.interest,
                this.tenureInMonths ? this.tenure : yearToMonths(this.tenure)
            );
        }
    }
    


    emiCalculator.html
    <template>
        <lightning-card
            variant="Narrow"
            title="EMI Calculator"
            icon-name="standard:bot"
        >
            <div class="slds-var-p-horizontal_small">
                <lightning-input
                    type="number"
                    variant="standard"
                    name="principal"
                    label="Principal"
                    placeholder="Enter Principal"
                    value={principal}
                    onchange={handleChange}
                ></lightning-input>
    
                <lightning-input
                    type="number"
                    variant="standard"
                    name="interest"
                    label="Interest"
                    placeholder="Enter Interest"
                    value={interest}
                    onchange={handleChange}
                ></lightning-input>
    
                <lightning-input
                    type="toggle"
                    variant="standard"
                    name="tenureInMonths"
                    label="Tenure In Months"
                    checked={tenureInMonths}
                    onchange={handleMonthToggle}
                ></lightning-input>
    
                <lightning-input
                    type="number"
                    variant="standard"
                    name="tenure"
                    label="Tenure"
                    placeholder="Enter Tenure"
                    value={tenure}
                    onchange={handleChange}
                >
                </lightning-input>
    
                <div>
                    Your EMI is <lightning-formatted-number
                        value={emi}
                        type="currency"
                    > </lightning-formatted-number>
                </div>
            </div>
        </lightning-card>
    </template>
    

Follow steps 6 through 7 to use the same code in other components, as needed. You can also create multiple utility components if needed.

Find the complete code at this GitHub repo: rahulgawale / lwc-emi-calculator

Thanks for visiting, please let me know your thoughts/ideas in the comments.

No comments :
Post a Comment

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