Lightning Web Components (LWC) are the modern standard for building fast, reusable, and secure UI on the Salesforce platform. In this post, we’ll explore the core principles, essential patterns, and expert tips to help you craft high-quality LWCs for any business scenario.
- Performance: Built on modern web standards for speed and efficiency.
- Reusability: Write modular, composable components.
- Ease of Testing: Clear separation of logic and UI for maintainable code.
- Future Proof: Aligns with evolving web platform APIs.
Each LWC consists of three main files:
component.js
— JavaScript logiccomponent.html
— HTML templatecomponent.js-meta.xml
— Metadata/configuration
Example:
// greeting.js
import { LightningElement, api } from 'lwc';
export default class Greeting extends LightningElement {
@api name = 'World';
}
<!-- greeting.html -->
<template>
<h1>Hello, {name}!</h1>
</template>
- Use
@api
,@track
, and@wire
decorators for reactive data. - Parent-to-child: Pass data with
@api
properties. - Child-to-parent: Fire custom events.
Best for: Fetching or mutating Salesforce data not available via standard UI APIs.
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class AccountList extends LightningElement {
@wire(getAccounts) accounts;
}
// Apex Controller
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
- Use standard DOM events or custom events for communication.
- Example: Notify parent of a button click.
// childComponent.js
handleClick() {
this.dispatchEvent(new CustomEvent('clicked'));
}
<!-- parentComponent.html -->
<template>
<c-child-component onclicked={handleChildClick}></c-child-component>
</template>
- Modularity: Break UI into small, single-purpose components.
- Composition: Nest, reuse, and combine components.
- Styling: Use SLDS or scoped CSS in
.css
files. - Testing: Write Jest tests for JS, use Lightning Testing Service for integration.
- Governor Limits: Minimize round-trips to Apex; use
@wire
and caching. - Security: Avoid exposing sensitive data via
@api
. Always use Lightning Data Service if possible.
// parent.js
handleGreeting(event) {
console.log('Received greeting:', event.detail.message);
}
<!-- parent.html -->
<template>
<c-child ongreet={handleGreeting}></c-child>
</template>
// child.js
handleButtonClick() {
this.dispatchEvent(new CustomEvent('greet', {
detail: { message: 'Hello from child!' }
}));
}
<!-- child.html -->
<template>
<button onclick={handleButtonClick}>Say Hi</button>
</template>
LWC empowers you to build powerful, enterprise-grade apps on Salesforce. Focus on reusability, leverage modern JavaScript, and always design for scalability and security.
Happy coding! ⚡️
Post a Comment