Sub topic 2
Anatomy of an LWC Component Bundle
Assume you know basic HTML, CSS, JavaScript classes, the DOM, and event listeners. An LWC component is a folder, called a bundle, whose files share one component name.
| File | Purpose |
|---|---|
| `helloGreeting.html` | Defines the rendered markup |
| `helloGreeting.js` | Holds state and behavior |
| `helloGreeting.css` | Styles this component |
| `helloGreeting.js-meta.xml` | Defines Salesforce metadata and placement |
helloGreeting/
├── helloGreeting.html
├── helloGreeting.js
├── helloGreeting.css
└── helloGreeting.js-meta.xmlThe HTML template uses expressions in braces. LWC evaluates {name} and inserts the current value into the page.
<!-- helloGreeting.html -->
<template>
<p>Hello, {name}!</p>
<input type="text" value={name} onchange={handleChange} />
</template>The JavaScript file exports a class that extends LightningElement, LWC’s base component class.
// helloGreeting.js
import { LightningElement } from 'lwc';
export default class HelloGreeting extends LightningElement {
name = 'World';
handleChange(event) {
this.name = event.target.value;
}
}Reactivity
Reactivity means the framework updates rendered output when tracked state changes. In modern LWC, assigning a new value to a class field used by the template schedules a rerender. The input handler changes name, so both the paragraph and input receive the new value.
Conditionals and lists
Template directives control repeated or optional markup. A list item needs a stable, unique key; the key helps LWC identify which item changed.
<template>
<template lwc:if={hasItems}>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>
<p lwc:else>No items found.</p>
</template>Public properties with `@api`
A field marked with @api is a public property. A parent component can set it. Without @api, the field is private to the component.
import { LightningElement, api } from 'lwc';
export default class CounterButton extends LightningElement {
@api label = 'Add';
count = 0;
}A component bundle maps framework files to a custom element whose template and state LWC manages.
Exercise
Why does items need a unique key when used with for:each?
Show answer
LWC uses the key to match each rendered DOM element with its data item during updates.