How to Create and Deploy LWC Component in Salesforce?

In Salesforce, LWC (Lightning Web Components) is used to build UI components using web standards, such as HTML, JavaScript, and CSS.

In this Salesforce tutorial, I will explain the complete process of creating and deploying LWC Components in Salesforce from scratch.

Create an LWC Component in Salesforce

In this example, we will create a Calculator as a Lightning component using LWC. To do this, you need to install VS Code on your system and then set up your Salesforce org using VS Code.

After setting up the org with VS Code, follow the steps below.

1. Create an LWC component:

To create an LWC component, you can execute the code below in the command terminal.

sfdx force:lightning:component:create -n myLWCComponent -d force-app/main/default/lwc

In the above code, replace the “myLWCComponent” with the name of the component. In this example, I have labeled it ‘Calculator’.

Another way to create an LWC component is to right-click on the LWC folder in the sidebar and select SFDX: Create Lightning Web Component.

How to create a LWC component in Salesforce

2. Add Code to the LWC Component:

As we create an LWC component, it will generate three files: .js, .html, and .xml files

Here, the HTML file defines the buttons and display of the calculator, while the JS file handles the logic, such as what happens when a button is clicked. The XML file will enable the calculator to be available in Salesforce, allowing you to use it on pages.

Now, open the .html file and enter the code below.

<template>
    <lightning-card title="LWC Calculator" icon-name="custom:custom63">
        <div class="slds-p-around_medium">
            
            <div class="slds-form-element">
                <lightning-input
                    type="text"
                    value={displayValue}
                    readonly
                    class="display"
                ></lightning-input>
            </div>
            
            <div class="slds-grid slds-wrap slds-gutters">
                <template for:each={buttons} for:item="button">
                    <div key={button.label} class="slds-p-top_x-large slds-p-right_large">
                        <lightning-button
                            label={button.label}
                            onclick={handleButtonClick}
                            data-value={button.value}
                            class="btn"
                        ></lightning-button>
                    </div>
                </template>
            </div>
        </div>
    </lightning-card>
</template>

In this code, we have designed the display and buttons for the calculator layout, utilizing Salesforce’s built-in components, such as <lightning-card> for styling and <lightning-button> for the buttons

To add padding between the buttons in the calculator, we have used the div tag:

<div key={button.label} class=”slds-p-top_x-large slds-p-right_large”>

3. Define the calculation logic in the JS file:

In this step, we will define the logic of the calculation and buttons, including what will happen when a specific button is clicked and the display is updated accordingly.

import { LightningElement, track } from 'lwc';

export default class Calculator extends LightningElement {
    @track displayValue = '0';
    firstOperand = null;
    operator = null;
    waitingForSecondOperand = false;

    buttons = [
        
         { label: '1', value: '1' },
        { label: '2', value: '2' },
        { label: '3', value: '3' },      
        { label: '4', value: '4' },
        { label: '5', value: '5' },
        { label: '6', value: '6' },
         { label: '7', value: '7' },
        { label: '8', value: '8' },
        { label: '9', value: '9' },
         { label: '0', value: '0' },
        { label: '*', value: '*' },
        { label: '/', value: '/' },
        { label: '-', value: '-' },
        { label: '.', value: '.' },
        { label: 'C', value: 'C' },
        { label: '=', value: '=' },
        { label: '+', value: '+' }
    ];

    handleButtonClick(event) {
        const { value } = event.target.dataset;

        if (value === 'C') {
            this.clear();
        } else if (value === '=') {
            this.calculate();
        } else if (['+', '-', '*', '/'].includes(value)) {
            this.handleOperator(value);
        } else {
            this.inputDigit(value);
        }
    }

    clear() {
        this.displayValue = '0';
        this.firstOperand = null;
        this.operator = null;
        this.waitingForSecondOperand = false;
    }

    inputDigit(digit) {
        if (this.waitingForSecondOperand) {
            this.displayValue = digit;
            this.waitingForSecondOperand = false;
        } else {
            this.displayValue = this.displayValue === '0' ? digit : this.displayValue + digit;
        }
    }

    handleOperator(nextOperator) {
        const inputValue = parseFloat(this.displayValue);

        if (this.firstOperand === null) {
            this.firstOperand = inputValue;
        } else if (this.operator) {
            const result = this.calculate();
            this.firstOperand = result;
            this.displayValue = String(result);
        }

        this.waitingForSecondOperand = true;
        this.operator = nextOperator;
    }

    calculate() {
        const inputValue = parseFloat(this.displayValue);

        if (this.operator === '+') {
            return this.firstOperand + inputValue;
        } else if (this.operator === '-') {
            return this.firstOperand - inputValue;
        } else if (this.operator === '*') {
            return this.firstOperand * inputValue;
        } else if (this.operator === '/') {
            return this.firstOperand / inputValue;
        }
        return inputValue;
    }
}

In the above code, we have used the following variables and functions to handle the functionalities of the LWC calculator.

Functions:

  • handleButtonClick: This runs when you click a button, checks which button was clicked, and calls the function according to that.
  • inputDigit: Adds a number to the display for the selected number.
  • handleOperator: Handles the arithmetic operator buttons (+.-,*,/).
  • calculate: To do the calculation for the selected number and operator, then return the result.
  • clear: to reset the calculator.

The variable we used, such as FirstOperand, represents the first digit that you select through buttons. WaitingForSecondOperand handles the logic when we select a clear button or when there is no need for a second number to be input.

4. Make components accessible to pages:

Now, go to the XML metadata file, and here, we will define where the Lightning component will be visible. Enter the below code inside the “LightningComponentBundle” tag.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

By selecting isExposed as true, we will make the component available to the org. Then, in the target tag, we define where we want to make the component accessible. For example, if you want to make it visible on the record page, then the target will be <target>lightning__RecordPage</target>.

5. Now, to deploy the LWC compoent to the Salesforce, go the click on the component in the left side bar and select “SFDX: Deploy this Source to Org“.

Create a Custom Lightning Component in Salesforce

6. Add the Lightning Component to the Salesforce Lightning Pages:

To add the calculator component to the lightning page, navigate to the Salesforce developer console and follow the steps below.

  • Navigate to the home page, app page, or record page where you want to deploy the component. Click on the settings icon and select Edit page.
  • In the Lighting Builder, navigate to the Components section and, from the Custom section, drag and drop the Calculator component onto the page layout. Then, click Save.
Add custom lwc component to the Lightning Page

As we click save, the component will be deployed on the Lightning page.

Salesforce Lightning custom LWC component

This way, we can create and deploy custom LWC components to the Lightning pages in Salesforce.

Conclusion

In this Salesforce tutorial, we have learned how to create and deploy a custom Lightning Web Component (LWC) in Salesforce from scratch. In the above steps, using the Salesforce interface and VS code, we designed the component’s structure with HTML, CSS, and JavaScript. We integrated Salesforce’s built-in components like <lightning-card> and <lightning-button> for the layout of the lightning component.

After creating the custom component, we have made it visible to the Lightning pages in the XML file. At last, we deployed the custom lightning component to the Lightning page using the Lightning app builder.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.