Slotted content page
Use slot elements to allow more control over non-critical parts of your component.
Overview
In this part we will:
- Use
slot
elements to allow customization.
Problem
In the previous section we allowed the header to be styled with a few CSS properties. We could continue to add more custom properties so even more of the header could be customized. For example, we could allow the user of our component to change the heading text by providing an attribute like title="My Bus Tracker"
.
An easier way to allow consumers of your component to have complete control is to use slots. In this part we want to allow the header to be replaced with a custom header. In the end it should look like:
How to Solve This Problem
- Provide a slot for the custom header passed to
bus-tracker
. - Use named slots to allow the
header
slot to be provided by the user. - Add custom styles to style the new header.
Technical requirements
Use this markup as the header that is passed into the component:
And use this CSS to style the header:
What you need to know
- How the slot element works.
- How to give slots names to allow multiple slotted content.
Slots
The slot has a curious effect when used within shadow DOM. It will take DOM within the custom element’s children and inject (but not move) those nodes as children of itself.
Default content can be specified by nesting DOM inside of the <slot>
element.
Named slots
Named slots are used when you want to take some of the children content, but not all of it. This is useful when you have multiple things to be customized. It works like <slot name="header">
, with the children needing to add a slot
attribute. <header slot="header">
.
Solution
✏️ Wrap the <header>
within the bus-tracker component with a <slot name="header">
. This will completely replace the header if a child element provides the slot="header"
attribute value.