ApexSensei

Lightning Web Components

A public guide to Lightning web components, with one page per topic and one short example on each page.

Introduction

A Lightning web component is a standard web component on Salesforce, guarded by Lightning Web Security, using shadow DOM unless you opt into light DOM.

Why LWC

Choose LWC for new interface work. It is standard HTML and JavaScript, and it can share a page with Aura.

Advantages

LWC stays fast in the browser, keeps styles inside shadow DOM, and runs under Lightning Web Security.

Browser support

LWC supports the latest stable Chrome, Edge, Firefox, and Safari. Internet Explorer is not supported.

Environment setup

Install the Salesforce CLI and the Salesforce Extension Pack, then run sf org login web on a Developer Edition org or a scratch org.

Hello world

A first component is a LightningElement class, a template, and a js-meta.xml file with isExposed and targets.

Data binding

The template reads JavaScript fields. Assign a new value in JavaScript and the template updates. It does not write back.

Controlled inputs

Set an input's value from JavaScript and copy the typed value back in onchange. LWC has no framework two-way binding.

Conditional HTML

Render a branch with lwc:if, lwc:elseif, and lwc:else. Retire the older conditional attributes.

Template looping

Repeat markup with for:each or iterator, and put a unique key on the first element in the loop.

Parent to child

A parent passes data by setting @api properties and can call @api methods on the child.

Child to parent

A child dispatches a CustomEvent. The parent listens on the child tag. Add bubbles or composed only when that listener is not enough.

Component to component

Components that do not share a parent talk through Lightning Message Service in lightning/messageService.

Lifecycle

The framework calls constructor, connectedCallback, renderedCallback, disconnectedCallback, and errorCallback. render() chooses the template.

Apex

Read with a cacheable @wire, save with an imperative call, and use the UI API when you do not need a custom Apex class.

Slots

A parent fills a default slot or a named slot. Light DOM changes how those slots and CSS behave.

Charts

Load third-party chart code from a static resource with loadScript. Lightning Web Security blocks many older builds.

Excel

A workbook built in the browser is fragile under Lightning Web Security. Use CSV or a file built on the server.

CLI

The command list lives in the Salesforce CLI reference and at /resources/cli. This page does not repeat it.