Whether you are transitioning from Aura or starting fresh with Salesforce development, mastering LWC fundamentals is key to building performant enterprise applications. Here are ten practical code examples covering essential LWC features and modern patterns.
1. Hello World Component
Every LWC component consists of an HTML template and an ES6 JavaScript class extending LightningElement.
<!-- helloWorld.html --> <template> <h1>Hello, World!</h1> </template>
// helloWorld.js
import { LightningElement } from 'lwc';
export default class HelloWorld extends LightningElement {}
Explanation: The template displays a static headline. The JavaScript file exports a default class that establishes the component lifecycle.
2. Property Binding and Modern Reactivity
Bind data dynamically from JavaScript to your HTML template using curly braces {property}.
<!-- propertyBinding.html -->
<template>
<h1>{greeting}</h1>
</template>
// propertyBinding.js
import { LightningElement } from 'lwc';
export default class PropertyBinding extends LightningElement {
greeting = 'Hello, Salesforce Developer!';
}
@track. Reserve @track exclusively for deeply nested object properties or mutating array elements in place.
3. Event Handling
Capture user interactions using declarative event listeners directly on HTML elements.
<!-- eventHandling.html -->
<template>
<lightning-button label="Click Me" onclick={handleClick}></lightning-button>
</template>
// eventHandling.js
import { LightningElement } from 'lwc';
export default class EventHandling extends LightningElement {
handleClick() {
console.log('Button clicked successfully!');
}
}
Explanation: The onclick directive connects the button click event to the handleClick handler in your JavaScript controller.
4. Conditional Rendering
Control what renders in the DOM based on component state using conditional directives.
<!-- conditionalRendering.html -->
<template>
<template lwc:if={showMessage}>
<p>This content is conditionally visible!</p>
</template>
<template lwc:else>
<p>Content is currently hidden.</p>
</template>
</template>
// conditionalRendering.js
import { LightningElement } from 'lwc';
export default class ConditionalRendering extends LightningElement {
showMessage = true;
}
lwc:if, lwc:elseif, and lwc:else directives instead of legacy if:true / if:false for cleaner logic and better runtime performance.
5. Iteration over Lists
Render repetitive data collections using the for:each directive with mandatory unique keys.
<!-- iteration.html -->
<template>
<ul class="ap-list">
<template for:each={fruits} for:item="fruit">
<li key={fruit.id}>{fruit.name}</li>
</template>
</ul>
</template>
// iteration.js
import { LightningElement } from 'lwc';
export default class Iteration extends LightningElement {
fruits = [
{ id: '1', name: 'Apple' },
{ id: '2', name: 'Banana' },
{ id: '3', name: 'Orange' }
];
}
Explanation: The for:each directive loops through the array, while the unique key attribute helps the virtual DOM engine optimize re-rendering.
6. Scoped CSS Styling
LWC encapsulates CSS via Shadow DOM scoping, preventing styles from leaking outside the component.
<!-- styling.html --> <template> <p class="highlight">Scoped custom styling in action.</p> </template>
/* styling.css */
.highlight {
color: #1f4e79;
font-weight: bold;
padding: 8px;
}
Explanation: CSS styles declared in your component bundle apply strictly to elements inside that specific component template.
7. Component Communication (Child to Parent)
Pass data upward from a child component to its parent using standard Custom Events.
<c-child-component> and attaches an event listener with the prefix on[eventname].
<!-- parentComponent.html -->
<template>
<c-child-component oncustomnotify={handleNotification}></c-child-component>
</template>
// parentComponent.js
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
handleNotification(event) {
const receivedPayload = event.detail;
console.log('Received payload:', receivedPayload);
}
}
<!-- childComponent.html -->
<template>
<lightning-button label="Send Data to Parent" onclick={sendMessage}></lightning-button>
</template>
// childComponent.js
import { LightningElement } from 'lwc';
export default class ChildComponent extends LightningElement {
sendMessage() {
const payload = { message: 'Hello from Child!' };
this.dispatchEvent(new CustomEvent('customnotify', { detail: payload }));
}
}
8. Apex Wire Service Integration
Fetch Salesforce data reactively by wiring an Apex method annotated with @AuraEnabled(cacheable=true).
<!-- apexWire.html -->
<template>
<template lwc:if={contacts.data}>
<ul class="ap-list">
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
</template>
// apexWire.js
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ApexWire extends LightningElement {
@wire(getContacts) contacts;
}
Explanation: The @wire decorator provisions data or error states automatically without requiring manual imperative invocations.
9. Helper and Local JavaScript Methods
Organize reusable logic inside modular private functions within your class.
<!-- localMethods.html -->
<template>
<lightning-button label="Process Action" onclick={handleClick}></lightning-button>
</template>
// localMethods.js
import { LightningElement } from 'lwc';
export default class LocalMethods extends LightningElement {
handleClick() {
this.formatAndLog('Action executed at: ' + new Date().toISOString());
}
formatAndLog(text) {
console.log(`[LWC Log]: ${text}`);
}
}
10. Lightning Data Service (LDS) Forms
Create and edit Salesforce records with built-in validation, FLS enforcement, and zero Apex code.
<!-- lightningDataService.html -->
<template>
<lightning-record-edit-form object-api-name="Account">
<lightning-messages></lightning-messages>
<div class="slds-grid slds-gutters">
<div class="slds-col">
<lightning-input-field field-name="Name"></lightning-input-field>
</div>
<div class="slds-col">
<lightning-input-field field-name="Phone"></lightning-input-field>
</div>
</div>
<div class="slds-m-top_medium">
<lightning-button label="Save Account" type="submit" variant="brand"></lightning-button>
</div>
</lightning-record-edit-form>
</template>
- Zero Server Code: Manages CRUD operations without writing Apex classes or unit tests.
- Security Baked In: Automatically enforces Field-Level Security (FLS) and Object Permissions.
- Cache Coordination: Shares reactive client-side cache across all components on the record page.