DEV Community

Frank Palmeri
Frank Palmeri

Posted on

Slot Composition

In developing our card web-component, our group has had the opportunity to familiarize ourselves with the <slot> element on html.

Application

The <Slot> function allows for code to be passed along multiple elements found throughout a component. In the context of the card, content such as headers, icons, and text are scaffolded in order to be displayed in the correct position on the page.

Example

The following code contains the information our group chose to display on our learning cards

updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName === 'type' && this[propName] === 'science') {
this.myIcon = 'beaker';
this.header = 'UNIT 1';
this.subheader = 'CHEM CONNECTION';
} else if (propName === 'type' && this[propName] === 'idea') {
this.myIcon = 'lightbulb';
this.header = 'UNIT 1';
this.subheader = 'LEARNING OBJECTIVES';
} else if (propName === 'type' && this[propName] === 'question') {
this.myIcon = 'question';
this.header = 'UNIT 1';
this.subheader = 'DID YOU KNOW?';
}
});
}

As you can see, the use of the commands this.myIcon, this.header, and this.subheader are used on each card, calling upon the information that is needed to be displayed pertaining to the categories 'LEARNING OBJECTIVES', CHEM CONNECTION', AND 'DID YOU KNOW'.

In order for the underlying information to be rendered under the correct header and sub-header, it is called upon using this.type and scaffolded using <slot> to format.

Example:

render() {
return html`
<learning-scaffold>
<learning-banner slot="banner" type=${this.type}>
<div class="header" slot="header">${this.header}</div>
<div class="subheader" slot="subheader">${this.subheader}</div>
</learning-banner>
<learning-body slot="body">
<slot></slot>
</learning-body>
</learning-scaffold>
`;
}

The use of a <slot> eliminates the need to manually input information throughout each element, making the development of a web component less redundant and more efficient.

The result of the code above has yielded the following result:

Image description

The repo containing the code used in the examples can be found below, and I encourage those who are looking to learn more about the <Slot> element on HTML to check it out.

Discussion (0)