Pass Configuration and Data to a Base Component
While many base components use slots to display content, some require you to pass configuration information and data to an attribute on a base component. Let's compare these two different approaches below.
For simple and maintainable code, we recommend using slots. For more information about slots, see Pass Markup to a Base Component Slot.
Attributes enable you to configure the base component to achieve specific behaviors. Base components that use the attributes pattern result in a flatter structure in the template. For example, you use the lightning-map
base component like this. Notice that the map-markers
attribute takes in the map configuration information.
However, using the attributes pattern in some cases can lead to complex code. For example, if lightning-button-group
uses an attribute to pass in button configuration information, your code can be hard to read and maintain. In this case, you pass in the configuration information to the lightning-button-group
component. And you pass the data and metadata for each button in the group as an object. Finally, you pass an array of these objects into an attribute on the button group component.
Since there are many base components that are button-based, such as the lightning-button-icon-stateful
and lightning-button-stateful
, the attribute for the configuration information must support that and its metadata as well. This can increase code complexity and impact code readability. That's why lightning-button-group
and many other base components uses the composition structure instead.
Using an attribute can be helpful in certain cases, as shown by base components such as lightning-checkbox-group
and lightning-select
. Generally, consider using an attribute if you want:
- Granular control for rendering elements within the component
- Easier validation checks on the metadata
- Rendering of native HTML inline for performance boost
Rendering native HTML inline can provide a performance boost, especially if you want to render the same element many times within a base component.
The lightning-select
base component uses the <select>
element and iteratively renders each option based on the configuration you provide. The base component internal markup looks like this, shortened for brevity.
Base components' internal markup is for demonstrative purposes only. They are an internal implementation that can change anytime.
When you use lightning-select
in your custom component, the base component renders this markup in the DOM.
In this case, providing an attribute for passing in configuration information and data allows developers to work with a flatter component surface.
See Also