Compose Components Using Slots Vs Data

When creating components that contain other components, consider the lifecycle of the component’s hierarchy using the declarative approach with slots, or the data-driven approach where a child component reacts to data changes from its parent.

A common pattern for building components declaratively looks like this.

This example has a c-parent component that uses a slot element. Although convenient for the consumer, you must manage the lifecycle of the content passed through the slot element.

There are several ways to manage content that’s passed into a slot.

  • Use the slotchange event. This is the recommended approach. slotchange bubbles up through the DOM but doesn’t cross the shadow boundary, enabling the parent component that contains the slot to react to it.
  • Use custom events to notify the parent component of changes to the child components, which enables you to make the methods on the component you are interacting with private. We no longer recommend this approach as we’re gradually migrating components to use native shadow, which enforces components to use the slotchange event.

Using the slotchange event with slots, you manage the lifecycle for the slot content between parent and child components. An example of this pattern is the lightning-button-group base component with child lightning-button components.

The parent lightning-button-group component contains a slot element with the onslotchange event to manage the lifecycle of content you pass in.

The base component examples are for demonstration purposes only. Base component internals are subject to change. We document changes to the features and behavior of components, but don’t document changes to their internals. See the Component Reference for the public attributes and methods on a base component.

The slotchange handler handles the updates to slotted elements when the content of the slot changes. In this case, the parent lightning-button-group component determines the CSS classes on the child lightning-button components based on the order they appear in the group—first, middle, last, or whether it’s the only button in the group.

Modify the button class using a getter.

Fire a register event so the lightning-button-group component can register the lightning-button components.

Notify the parent when the child component is no longer available.

Using the data-driven approach, the component gets the changes in a reactive way when data changes.

This example composes a child component using a data-driven approach.

To pass in data, use a JavaScript object. The child component reacts to data changes exclusively from its parent.

A data-driven approach is recommended when you have a complex use case. An example of a base component that’s created using the data-driven approach is lightning-datatable.

See Also