Sub topic 3
Rendering Child Components from a List
Assume you know basic Lightning web components, JavaScript classes, template expressions, and spread syntax. This chapter focuses on parent-to-child communication in repeated components.
Rendering a list with `for:each`
Use for:each when the parent has an array and needs one child component for each item. Put a unique key on the repeated child. The key helps Lightning track each child when the array changes.
<!-- taskBoard.html -->
<template>
<template for:each={tasks} for:item="task">
<c-task-card
key={task.id}
heading={task.name}
priority={task.priority}>
</c-task-card>
</template>
</template>The child receives heading and priority through public @api properties. A property such as priority becomes the priority attribute in markup. A JavaScript name such as taskName becomes task-name.
Validate input with a getter and setter
A setter runs when the parent gives the child a new value. It can validate or transform that value. Copy arrays before changing them because data passed from a parent is read-only from the child’s perspective.
// taskList.js
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
get tasks() {
return this._tasks;
}
set tasks(value) {
this._tasks = Array.isArray(value) ? [...value] : [];
}
sortByName() {
this._tasks = [...this._tasks].sort((a, b) =>
a.name.localeCompare(b.name)
);
}
}Call a child method
Use an @api method when the parent needs an action, rather than a value.
// searchBox.js
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focus() {
this.template.querySelector('input').focus();
}
}
// app.js
handleShowSearch() {
this.template.querySelector('c-search-box').focus();
}Choose the right communication tool
- Use properties for values flowing from parent to child.
- Use a slot when the parent supplies markup or content, not just data.
- Use a custom event when the child needs to send information upward.
- Use methods for commands such as
focus()orreset().
Common pitfalls
- Do not omit
key, or use an array index when items can be reordered. - Match public property names to the correct kebab-case attributes.
- Do not mutate received arrays or objects directly.
- Check that the child selector matches its component folder name.
- Query a child only after it has rendered.
Exercise
Why should a repeated child use key={task.id} instead of an array index?
Show answer
A stable unique key lets Lightning preserve the correct child when items are added, removed, or reordered.