Compose Components
It’s useful to compose apps and components with a set of smaller components to make the code more reusable and maintainable. The lightning
namespace contains many base components, such as lightning-button
, that you can use to build your components.
Let’s look at a simple app composed of components. The markup is contrived because we want to illustrate the concepts of owner and container. In a real app, the number of c-todo-item
instances would be variable and populated dynamically in a for:each
loop.
The owner is the component that owns the template. In this example, the owner is the c-todo-app
component. The owner controls all the composed components that it contains. The owner can:
- Set public properties on composed components
- Call methods on composed components
- Listen for any events fired by the composed components
A container contains other components but itself is contained within the owner component. In this example, c-todo-wrapper
is a container. A container is less powerful than the owner. A container can:
- Read, but not change, public properties in contained components
- Call methods on composed components
- Listen for some, but not necessarily all, events bubbled up by components that it contains.
When a component contains another component (which can in turn contain other components), we have a containment hierarchy. In the documentation, we sometimes talk about parent and child components. A parent component contains a child component, like this:
In this simplified outline of a project directory, parentComponent
and childComponent
are nested in the same lwc
folder. The parent-child relationship is defined in parentComponent.html
.
See Also
- Lightning Web Components and Aura Components Working Together
- Set Properties on Children
- Salesforce DX Developer Guide: Salesforce DX Project Structure and Source Format