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
The template of <FancyButton>
looks like this:
js
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
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
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
React Essentials
Building Your Application
TypeScript