Index › 12. Slots
Explore how slots provide a convenient means of passing larger pieces of content to be rendered in your components and fragments.
Topics covered
- Introduction to slots
In the previous tutorial, you saw how to use components and fragments to remove redundancy from your code.
You can think of components and fragments as custom HTML tags. Just like HTML tags, you can set attributes on them (what we call props in Kitten). But some standard HTML tags, in addition to having attributes, can also contain content inside themselves.
The <h1> tag, for example, takes the text you want to display as a first-level heading in between its opening and closing tags, like this:
<h1>I’m the very model of a first-level heading</h1>
In Kitten, you can do the same thing with custom tags (components and fragments) by passing content into them using a special prop called a slot.
For example, if you have the following component:
export default ({lineStyle = 'solid', SLOT}) => kitten.html`
<div class='box'>
${SLOT}
<style inline>
@scope {
:scope {
padding: 1em;
border: 1px ${lineStyle} CornflowerBlue;
}
em { color: DarkViolet; }
}
</style>
</div>
`
You can slot content into it like this from your page:
import box from './box.component.js'
export default () => kitten.html`
<h1>Page</h1>
<p>This is the page.</p>
<${box} lineStyle=dashed>
<h2>Slotted content</h2>
<p class='override'>This is <em>slotted content</em> from the page.</p>
</>
<p>This is the page again.</p>
<style>
body { font-family: sans-serif; }
/* Example of using the cascade to override styles in components for slotted content. */
.override em { color: DeepPink; }
</style>
`
HTML, CSS, and Markdown fragments support slots just like JavaScript fragments do (including named slots) and they can interpolate their props (${props.name}).
A fragment renders slotted content only where it interpolates ${SLOT}. So, you could, for example, add ${SLOT} as the last line of the index.fragment.css file from the previous tutorial:
/* … */
${SLOT}
And then extend its styles like this:
import styles from './index.fragment.css'
// …
return kitten.html`
<${styles}>
h1 {
color: red;
}
</>
<h1>Aral’s Public Fediverse Timeline</h1>
…
`
Although, you could, just as easily, add another <style>…</style> section to your code too.
While HTML, CSS, and Markdown fragments are not as flexible as JavaScript fragments and components, you might find them useful as your editor might give you better language intelligence than in HTML and CSS tagged template strings, to save on one level of indentation, or for organisational preferences.
Well, that was a short and sweet introduction to slots and yet you can probably already think of a few good use cases for them. If you were thinking that they sound like they’d be useful for layout, you’re correct.
Let’s learn about named slots and explore the relationship between slots and layout components next.
Next tutorial: Layout components