DEV Community

spb5732
spb5732

Posted on

Using slot with custom web componnents.

when creating custom web components the slot tag can be very useful. The slot tag allows you to pass html content into the shadowroot of your custom element.

When would you use the slot tag?

  • An example of when I have had to use the slot tag was when I was coding my custom web component learning card. -The card had a body section that needed to have support for any html content.

slime-card:

Image description

How to use slot.

  • If you have a blank slot any content will be passed from inside the custom element into the blank slot.
  • If you have a named slot you need to pass the slot attribute with the correct name into the html content.

examples below:

index.html


<custom-web-component>

<span>This will be put into the blank slot</span>

</custom-web-component>


<custom-web-component>

<span slot="s1">This will be put into s1 slot!</span>

</custom-web-component>

Enter fullscreen mode Exit fullscreen mode

custom-web-component.js

render(){ return hml`
<div id="custom-web-component">
<slot></slot>
<slot name="s1"></slot>
</div>`;
}
Enter fullscreen mode Exit fullscreen mode

In the slot tag allows you to pass html content into a custom web component. It also makes it really easy to pass content from the top level of a web component down to the bottom level. This makes alot of sense when you break down a custom web component into smaller sub components.

For example

  • The learning card was broken down into icon, header, body , and card as a whole
  • When using the card as a whole, info can be passed from the slot of the card as a whole into the slot for the body component. This allows custom web components to be very flexible.

Top comments (0)