How to Create Custom Components Using LWC

In the world of Salesforce development, Lightning Web Components (LWC) have become one of the most powerful ways to build modern, fast, and efficient user interfaces. LWC is built on the latest web standards, making it lightweight and high-performing. If you’re a Salesforce developer looking to build custom components that are reusable, responsive, and scalable, understanding LWC is essential.
This comprehensive guide will walk you through how to create custom components using LWC, from setup to deployment, along with best practices and tips.
Table of Contents
What Are Lightning Web Components (LWC)?
Lightning Web Components (LWC) is a modern framework developed by Salesforce that allows developers to build custom, reusable components. It is based on native web standards like Web Components, Custom Elements, Shadow DOM, and ES Modules, which makes the development process faster and more aligned with modern JavaScript.
Why Choose LWC?
1. Performance:
Faster and more lightweight compared to older frameworks like Aura.
2. Standards-Based:
Uses modern JavaScript, HTML, and CSS.
3. Secure:
Built-in security with Salesforce Locker Service.
4. Reusable:
Components can be reused across different Salesforce pages and apps.
5. Seamless Integration:
Direct access to Salesforce data via Apex and Lightning Data Service.
Step 1: Create a Salesforce DX Project
First, you need to create a Salesforce DX (SFDX) project to manage your component development.
Command to create a project:
sfdx force:project:create –projectname myLwcProject
Navigate to your project directory:
cd myLwcProject
Authorize Salesforce Org to connect your project:
sfdx force:auth:web:login -a DevHub
Step 2: Create a Lightning Web Component
Once your project is set up, create a new component using the following command:
sfdx force:lightning:component:create –type lwc –componentname helloWorld –outputdir force-app/main/default/lwc
This will generate a folder named helloWorld
containing three key files:
helloWorld.html
: The template for UI.helloWorld.js
: The JavaScript controller for logic.helloWorld.js-meta.xml
: The metadata file that controls visibility and configuration.
Step 3: Understanding the Component Structure
1. HTML File (User Interface)
This file defines the visual structure of your component using standard HTML along with LWC-specific syntax.
Example:
<template>
<h1>Hello, {name}!</h1>
<lightning-input label=”Enter your name” onchange={handleChange}></lightning-input>
</template>
2. JavaScript File (Logic Layer)
Handles the component’s data and logic.
import { LightningElement } from ‘lwc’;
export default class HelloWorld extends LightningElement {
name = ‘World’;
handleChange(event) {
this.name = event.target.value;
}
}
3. Meta XML File (Configuration Layer)
Controls where the component can be used (App Builder, Record Pages, etc.).
<?xml version=”1.0″encoding=”UTF-8″?>
<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”helloworld”>
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<targets>lightning__AppPage</targets>
<targets>lightning__RecordPage</targets>
<targets>lightning__HomePage</targets>
</targets>
</LightningComponentBundle>
Step 4: Deploy Component to Salesforce Org
To make your component available in Salesforce:
Deploy source:
sfdx force:source:push
Now, you can use this component in Lightning App Builder and Record Pages.
Step 5: Use Your Component in Lightning App Builder
- Go to Salesforce Setup.
- Navigate to Lightning App Builder.
- Create or edit a page (App/Home/Record Page).
- Find your helloWorld component in the custom components list.
- Drag and drop it onto the page.
- Save and activate the page.
Congratulations! Your first custom LWC component is live.
Step 6: Adding CSS Styling to Your Component
To add custom styling, create a CSS file named helloWorld.css
inside the component folder.
Example:
h1 {
color: blue;
font-size: 24px;
}
Salesforce also allows scoped styles using :host
selector.
Example:
:host {
display: black;
border: 1px solid #ddd;
padding: 10px;
border-radius: 8px;
}
Step 7: Communicating Between Components
Sometimes, you may need to share data between components. You can achieve this using public properties, custom events, and Apex methods.
Using Public Properties:
export default class ChildComponent extends LightningElement {
@api message; // Public property
}
Using Custom Events:
this.dispatchEvent(new CustomEvent(‘myevent’, { detail: ‘Data from child’ }));
Handling Events in Parent:
<c-child-component onmyevent={handleEvent}></c-child-component>
Apex Method (Server-side call):
import getAccounts from ‘@salesforce/apex/AccountController.getAccounts’;
connectedCallback() {
getAccounts().then(result => {
this.accounts = result;
}).catch(error => {
console.error(error);
});
}
Step 8: Best Practices for LWC Development
1. Follow Naming Conventions: Use kebab-case for component names.
2. Use Decorators Properly: @api
, @track
, @wire
as needed.
3. Avoid DOM Manipulation: LWC handles DOM updates, so avoid manual changes.
4. Modular Components: Keep components small, reusable, and focused on a single responsibility.
5. Handle Errors Gracefully: Always handle exceptions, especially with Apex calls.
6. Security First: Never expose sensitive data. Use Salesforce Locker Service guidelines.
Step 9: Debugging and Testing
1. Console Logs: Use console.log()
to debug in browser dev tools.
2. LWC Jest Tests: Write unit tests using Salesforce-supported Jest framework.
3. Salesforce Lightning Testing Service (LTS): For end-to-end testing.
4. Browser DevTools: Inspect components using Chrome DevTools.
Conclusion
Building custom components using Lightning Web Components is a crucial skill for Salesforce developers aiming to create modern, responsive, and reusable UI elements. By leveraging JavaScript, HTML, and CSS, developers can build powerful custom solutions directly integrated with Salesforce data and workflows.