LWC - Salesforce

Getting Started with LWC


Now that you have set up your development environment, it’s time to dive into Lightning Web Components (LWC). In this section, you will learn about the basic structure of an LWC, how to create one, deploy it to Salesforce, and debug it.

Each topic will include in-depth explanations, examples, and step-by-step guides to ensure you’re fully engaged and equipped to start building with LWC.

This section will help you get started with LWC by covering:

  • The basic structure of an LWC component
  • Creating your first LWC
  • Deploying an LWC component to Salesforce
  • Debugging techniques for efficient development

Let’s dive in!


Basic Structure of an LWC

A Lightning Web Component consists of three main files:

Basic Structure of an LWC

  1. HTML File (.html) – Defines the component's structure (UI) and layout.
  2. JavaScript File (.js) – Handles the component's logic and behavior.
  3. Meta Configuration File (.xml) – Declares the component’s visibility and usage in Salesforce.

Example Folder Structure of an LWC Component


myFirstComponent/

  • myFirstComponent.html
  • myFirstComponent.js
  • myFirstComponent.js-meta.xml
  • myFirstComponent.css (Optional)

Understanding Each File with an Example


1. HTML File (.html)

Defines the structure of the component using standard HTML and LWC directives.

myFirstComponent.html


<template>
  <lightning-card title="My First LWC">
    <div class="slds-m-around_medium">
      <p>Hello, {name}!</p>
    </div>
  </lightning-card>
</template>


2. JavaScript File (.js)

Handles data and business logic.

myFirstComponent.js


import { LightningElement } from 'lwc';

export default class MyFirstComponent extends LightningElement {
  name = 'Salesforce Developer';
}


3. Meta Configuration File (.xml)

Controls visibility and where the component can be used in Salesforce.

myFirstComponent.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>
<lightningcomponentbundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiversion>62.0</apiversion>
  <isexposed>true</isexposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>


4. CSS File(.css)

Defines the component's styling (Optional) .

myFirstComponent.css


p {
  font-size: 16px;
  color: #333;
}

Key Points:

  • HTML File: Uses the <template> tag to define the component's structure. You can use Lightning Base Components like <lightning-card> for pre-styled UI elements.
  • JavaScript File: Exports a class that extends LightningElement. This class contains the component's logic and properties.
  • Configuration File: Defines metadata like API version, exposure, and target locations (e.g., App Page, Record Page).
  • CSS File: Styles are scoped to the component, meaning they won’t affect other components.

Output:

Now that you understand the structure, let’s create an LWC!