Getting Started

Slots

Slots

This page assumes you've already read the Components Basics. Read that first if you are new to components.

Watch a free video lesson on Spec School

Slot Content and Outlet

We have learned that components can accept props, which can be JavaScript values of any type. But how about template content? In some cases, we may want to pass a template fragment to a child component, and let the child component render the fragment within its own template.

js

<FancyButton>
  Click me! <!-- slot content -->
</FancyButton>

The template of <FancyButton> looks like this:

js

<button class="fancy-btn">
  <slot></slot> <!-- slot outlet -->
</button>

The <slot> element is a slot outlet that indicates where the parent-provided slot content should be rendered.

Render Scope

Slot content has access to the data scope of the parent component, because it is defined in the parent. For example:

js

<span>{{ message }}</span>
<FancyButton>{{ message }}</FancyButton>

Expressions in the parent template only have access to the parent scope; expressions in the child template only have access to the child scope.

Here both {{ message }} interpolations will render the same content. Slot content does not have access to the child component's data. Expressions in Spec templates can only access the scope it is defined in, consistent with JavaScript's lexical scoping. In other words:

Fallback Content

There are cases when it's useful to specify fallback (i.e. default) content for a slot, to be rendered only when no content is provided. For example, in a <SubmitButton> component:

js

<button type="submit">
  <slot></slot>
</button>

We might want the text "Submit" to be rendered inside the <button> if the parent didn't provide any slot content. To make "Submit" the fallback content, we can place it in between the <slot> tags:

js

<button type="submit">
  <slot>
    Submit <!-- fallback content -->
  </slot>
</button>

React Essentials

Building Your Application

TypeScript