Sub topic 11
Passing data to a child with @api properties
This chapter assumes you can build a basic Lightning Web Component bundle. It also assumes you know what a reactive field is, and that you can write a getter and bind it with { }. Here you will see how a parent component hands a value to a child component, and what the child may and may not do with it.
The public property contract
Every field on a component class is private by default. A parent template cannot see it. To let a parent set a value, the child marks the field with the @api decorator. A decorator is an annotation placed before a class member that changes how the framework treats it. @api makes the member part of the component's public interface.
// productCard.js
import { LightningElement, api } from 'lwc';
export default class ProductCard extends LightningElement {
@api productName;
get heading() {
return this.productName ? this.productName.toUpperCase() : 'UNNAMED PRODUCT';
}
}productName is now public. The heading getter is still private, and only this component's template can bind to it. The child template does not need to know where the value came from:
<!-- productCard.html -->
<template>
<h2>{heading}</h2>
</template>The parent then sets the public property as if it were an HTML attribute:
<!-- parent.html -->
<template>
<c-product-card product-name={selectedName}></c-product-card>
</template>The braces work the same way as in any other binding. The parent evaluates selectedName on its own class and passes the result to the child's productName.
Name mapping between JavaScript and HTML
JavaScript property names are camelCase, but HTML attribute names are case-insensitive. LWC resolves this with a fixed convention. You write the property in camelCase in the child's class and in kebab-case (lowercase words joined by hyphens) in the parent's markup. The component tag follows a similar rule, with the namespace first.
| Where | Written as |
|---|---|
| Child class property | `productName` |
| Parent template attribute | `product-name` |
| Child class name | `ProductCard` |
| Child folder and file names | `productCard` |
| Tag in the parent template | `c-product-card` |
The most common mistake here is writing productName={selectedName} in the parent template. The attribute is then not recognized as the public property, and the child never receives the value. No error is raised.
How data flows
Data moves in one direction: from the parent's field, through the parent's template, into the child's public property, and on into the child's template. The following diagram shows the path.
When the parent reassigns selectedName, the parent re-renders and passes the new value to the child. The child's productName changes, so the child re-renders too. You do not write any code to trigger that. Public properties are reactive, as fields are.
Here is a complete parent that changes the value over time:
// parent.js
import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
products = ['pen', 'notebook', 'stapler'];
index = 0;
get selectedName() {
return this.products[this.index];
}
handleNext() {
this.index = (this.index + 1) % this.products.length;
}
}<!-- parent.html -->
<template>
<c-product-card product-name={selectedName}></c-product-card>
<button onclick={handleNext}>Next product</button>
</template>Each click increments index. That re-renders the parent, selectedName returns a new string, and the child's heading changes from PEN to NOTEBOOK to STAPLER. The parent binds to a getter here, which is allowed anywhere a property reference is allowed.
Passing literals instead of bindings
If the value is a fixed string, you can write it directly and leave out the braces:
<c-product-card product-name="Pen"></c-product-card>Without braces, the value is always a string. For other types, bind a property from the parent's class. Writing quantity="3" passes the string "3", not the number 3. If the child does arithmetic on it, you will get string concatenation or a NaN instead of a sum. A bare attribute such as <c-flag active></c-flag> is treated as true. For this reason, give boolean public properties a default of false, and never a default of true. A parent cannot turn off a property that starts as true by leaving the attribute out.
The child must not overwrite what it receives
The owner of a public property's value is the parent. The child reads it. The rules differ slightly by type:
- For primitives (strings, numbers, booleans), the child can technically assign to its own
@apifield, but doing so makes the child's state disagree with what the parent believes it passed. The next parent re-render can overwrite the change. Treat the property as read-only inside the child. - For objects and arrays, the value the child sees is a read-only view. Setting
this.item.name = 'x'whereitemcame from a parent fails with a mutation error at runtime.
If the child needs a changed version of the data, it should copy it into a private field or compute a derived value with a getter. If the parent should learn about a change, the child dispatches an event. Events are covered in a later chapter. The heading getter above is the pattern to follow. It reads the public property and returns a modified value without touching the original.
// productList.js, a child that receives an array
import { LightningElement, api } from 'lwc';
export default class ProductList extends LightningElement {
@api products = [];
get sortedProducts() {
// slice() copies the array, so the original is not sorted in place
return this.products.slice().sort();
}
}Calling sort() directly on this.products would try to mutate the read-only array and throw. Copying first is the fix.
When the parent mutates an object in place
Suppose the parent passes an object and later changes one of its properties in place:
// parent.js, a pattern that can go stale
import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
product = { name: 'pen' };
rename() {
this.product.name = 'notebook';
}
}Reassigning a field always re-renders. In-place changes to the contents of an object are observed only for fields that are tracked, as the earlier chapter on @track explained. In current LWC, the child can still miss such a change, because the reference it holds has not changed. The reliable approach is to replace the value in the parent:
rename() {
this.product = { ...this.product, name: 'notebook' };
}The spread syntax creates a new object. The parent's field now holds a new reference, so the child receives a new value and re-renders.
Timing: the property may be undefined at first
A child is created first and receives its public properties just after. Inside the constructor, this.productName is not yet set. By the time connectedCallback runs, the values from the parent's template are in place, with one exception: values that depend on data the parent has not loaded yet. If the parent gets its data from a server call, the first render passes undefined, and a later render passes the real value.
For this reason, write getters in the child that tolerate an empty value. The heading getter checks for a falsy productName before calling toUpperCase(). Without that check, the first render would throw a TypeError on undefined. If the child needs to run code when a value arrives, the next chapter shows how a setter on the public property can do that.
Reserved and restricted names
Some names are not allowed for public properties. Pick names that avoid these:
- Names that start with
data, such asdatasetordataValue, because they collide withdata-*HTML attributes. - Names that start with
on, because they look like event handler attributes. - Names that match global HTML attributes, such as
class,slot,style,title,hiddenandid, where the platform already gives them meaning.
If you need a title, use a name like cardTitle instead.
Summary of the rules
- Mark a field
@apito expose it. Everything else stays private. - Use camelCase in the child class and kebab-case in the parent markup.
- Use braces to pass a value from the parent's class, and no braces for a fixed string.
- Treat received values as read-only. Derive new values with getters and copy before sorting or changing.
- Replace objects in the parent instead of changing them in place, so the child sees a new reference.
- Write child getters that handle
undefined.
Exercise
A child declares @api itemCount = 0;. The parent template contains <c-badge itemCount={total}></c-badge>, and the badge always shows 0 even though total is 12. What is wrong, and how do you fix it?
Show answer
The attribute is written in camelCase, so it is not mapped to the public property. Use the kebab-case form: <c-badge item-count={total}></c-badge>.
Exercise
A child receives @api tags (an array from its parent) and calls this.tags.sort() in a getter. The component throws an error at runtime. Rewrite the getter so it returns a sorted list without error.
Show answer
The array from the parent is read-only, so it cannot be sorted in place. Copy it first: get sortedTags() { return this.tags.slice().sort(); }. A spread copy, [...this.tags].sort(), also works.