DEV Community

Jimmy Kane
Jimmy Kane

Posted on

<Slot> in LitElement

When designing new web components, the goal is to keep them as abstract as possible so that they can be used over and over again.  If web components are made specifically for a given project and need something similar for another, you'll just be coping the same exact code over and over again.  That would violate the DRY coding principal or simply put "Don't Repeat Yourself".
 
In a previous post, I talked about how I am developing a card like the one below.  One of the assignment criteria is to have 4 components: the entire card itself, a scaffold of the card, the icon, and banner.  To keep the card dynamic, all text fields and the icon can be set thanks to slots and I will show you how we have done that thus far.
 
Image description

Image description

 
Lets start with the inner most component the Learning-Icon.  This is a relatively simple component as it will display a different a SVG based on the type attribute passed into it.
 
Image description

 
The Learning-Icon is then used within the Learning-Banner but say that I later create an Icon called Quiz-Icon.  If I hardcoded in the Learning-Icon the banner will be tied to just the learning card.  To add this flexibility I made use of the tag and named it "icon".  Same thing applies to the headings, to keep the styling and content of them open to the user I also used slots and gave them names.  You do not need to name your slots, if you don't, it will fill slots in the order you pass them in.  However it just takes an extra attribute just to ensure that slots and their values are paired correctly; so why not do it.
 
Image description

 
As mentioned above say I want to have a Math-Card or a Computer-Card, they are both basically the same.  They both will have a header of some kind, and some sort of content, thus we will create a template with some base styling and framework.  I called this Learning-Scaffold as we plan to this card used in a learning context.  This card has two named slots, one for the banner and the other for the content.

Image description

 
Now bringing it all together we define a Learning-Card which implements a Learning-Scaffold.  From here I define all of these components and all of their slots.

Image description

Top comments (0)