DEV Community


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.


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:



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



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


Enter fullscreen mode Exit fullscreen mode


render(){ return hml`
<div id="custom-web-component">
<slot name="s1"></slot>
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.

Discussion (0)