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.

1<!-- todoApp.html -->
2<template>
3  <c-todo-wrapper>
4    <c-todo-item item-name="Milk"></c-todo-item>
5    <c-todo-item item-name="Bread"></c-todo-item>
6  </c-todo-wrapper>
7  <template></template
8></template>

Owner 

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

Container 

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.

Parent and child 

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:

parentComponent.html
1<template>
2  <div>
3    <child-component></child-component>
4  </div>
5</template>

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.

1force-app
2    ├──main
3        ├──default
4            ├──aura
5            ├──...
6            ├──lwc
7                ├──parentComponent
8                    ├──parentComponent.css
9                    ├──parentComponent.html
10                    ├──parentComponent.js
11                ├──childComponent
12                    ├──childComponent.css
13                    ├──childComponent.html
14                    ├──childComponent.js

See Also