We explore some more advanced component composition patterns.
This article is part of the series starting with Exploring Salesforce Lightning Web Components: Part 1.
Calling Child Methods
So far we have explored parent to child communication in the form of passing primitives to a reactive property (using the @api decorator). But it is not obvious how to enable the child component run code (triggering side-effects) based on changes to that property.
One solution is to have the parent call exposed methods on children. In this example, we create a component, Player, that exposes two methods (play and pause) that is used by the parent HelloWorld component.
- Notice that in addition to changing the playing property, we have an opportunity to trigger side effects in the play and pause methods
- Unlike the Salesforce documentation on calling methods on child components, here we use the renderedCallback method to first store a reference to the player once HelloWorld renders
Using renderedCallback Instead
One problem with the previous approach is that we have complicated the Player component’s interface; introducing two methods. Another solution is to simply pass a reactive property, e.g., playing, and detecting changes (and triggering side-effects) in the Player component.
- We use the renderedCallback component lifecycle method to perform the side-effects
Cross-Cutting Concerns and Slots
One common pattern is the need to apply some cross-cutting concern; like styling a frame around content. In this context, cross-cutting means a repeatable pattern that is used across the component tree. To achieve this we can use Web Component slots.
In this example, we create a Frame component that wraps its children in a div with a yellow background. We then use it in the HelloWorld component.
- Without extraordinary effort, a component does not have the ability to interact with the content in its slots; thus this pattern is mostly useful in simply styling the container of the slot content
- The slot content is not part of the component’s Shadow DOM, i.e., any component CSS rules do not apply to the slot content
In the next article, Exploring Salesforce Lightning Web Components: Part 7, we explore another pattern for inter-component communication.