Exploring Salesforce Lightning Web Components: Part 6

We explore some more advanced component composition patterns.

Image for post
Image for post

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.

Image for post
Image for post

Here is the Player’s HTML and JavaScript:

Observations:

  • Notice that in addition to changing the playing property, we have an opportunity to trigger side effects in the play and pause methods

Here is the updated HelloWorld HTML and JavaScript:

Observations:

  • Here we use the normal JavaScript querySelector method to obtain a reference to the Player component

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 refactor the Player components HTML and JavaScript:

Observations:

  • We use the renderedCallback component lifecycle method to perform the side-effects

With these changes, our HelloWorld component’s HTML and JavaScript are simplified:

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.

Image for post
Image for post

We create the Frame component’s HTML, JavaScript, and CSS:

We then use the Frame component in the HelloWorld component; the HTML and JavaScript:

Observations:

  • 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

Next Steps

In the next article, Exploring Salesforce Lightning Web Components: Part 7, we explore another pattern for inter-component communication.

Written by

Broad infrastructure, development, and soft-skill background

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store