Sub topic 1
Parents, children and the c- tag
Prerequisites
Assume you can create a Lightning web component (LWC), use JavaScript classes and modules, and write template expressions such as {propertyName}.
Parents, children and the `c-` tag
A parent component contains another component. The contained component is the child. In markup, a custom LWC uses the c- prefix followed by its component folder name. For example, a component folder named taskCard is used as <c-task-card>.
Exposing a child property with `@api`
A public property is a value that a parent can set. In an LWC, import the api decorator and place @api before the property.
// taskCard.js
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api heading;
@api priority = 'normal';
}The child can use these properties in its template:
<!-- taskCard.html -->
<template>
<article>
<h3>{heading}</h3>
<p>Priority: {priority}</p>
</article>
</template>A public property creates a data interface between the two components. The child owns the property definition, while the parent supplies its value.
Naming: camelCase in JavaScript, kebab-case in markup
JavaScript property names commonly use camelCase, such as taskTitle or isUrgent. HTML attributes use kebab-case, so taskTitle becomes task-title and isUrgent becomes is-urgent.
<template>
<c-task-card
task-title="Write documentation"
is-urgent>
</c-task-card>
</template>Use the exact converted name. A mismatched attribute does not set the intended public property.
> callout note > A bare Boolean attribute such as is-urgent represents true when present. Boolean public properties should normally default to false.
Binding values from the parent's JavaScript
A quoted value is a literal string. To pass a value from the parent’s JavaScript class, use a template binding without quotes.
<!-- taskBoard.html -->
<template>
<c-task-card
heading={nextHeading}
priority={nextPriority}>
</c-task-card>
</template>// taskBoard.js
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
nextHeading = 'Review pull request';
nextPriority = 'high';
}When the parent’s values change, the framework updates the child’s public properties and rerenders affected template output.
Exercise
How do you pass the parent field displayName to a child property named userName?
Show answer
Declare @api userName in the child, then write <c-child user-name={displayName}></c-child> in the parent template.