Kitten

Explore how slots provide a convenient means of passing larger pieces of content to be rendered in your components and fragments.

Topics covered

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:

Box.component.js

export default ({lineStyle = 'solid', SLOT}) => kitten.html`
  <div class='Box'>
    ${SLOT}
  </div>

  <style>
    .Box {
      padding: 1em;
      border: 1px ${lineStyle} CornflowerBlue;
    }
    .Box em { color: DarkViolet; }
  </style>
`

You can slot content into it like this from your page:

index.page.js

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>
`

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

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.