Slots

Where the Children Go

Slots

`<slot />` is where a component's children render. Fallback content is between the opening and closing slot tags.

3 min read Level 1/5 #astro#slots#components
What you'll learn
  • Use the default `<slot />`
  • Provide fallback content
  • Recognize the React/Vue "children" equivalent

When you put content between a component’s opening and closing tags, Astro renders it where the component uses <slot />.

The Default Slot

---
// Card.astro
---
<section class="card">
  <slot />
</section>
---
import Card from "../components/Card.astro";
---

<Card>
  <h2>Title</h2>
  <p>Body</p>
</Card>

The <h2> and <p> render inside the <section>. Same idea as React’s children prop.

Fallback Content

Anything between <slot> and </slot> is fallback — rendered when the caller passes nothing.

---
// Card.astro
---
<section class="card">
  <slot>
    <p class="muted">(empty card)</p>
  </slot>
</section>
<Card />                   {/* renders "(empty card)" */}
<Card><p>Hello</p></Card>  {/* renders <p>Hello</p>    */}

Slots With Names — Preview

For multi-region layouts (header, sidebar, footer), you’ll want named slots. We cover them in chapter 3, but here’s a taste:

---
// Layout.astro
---
<div class="layout">
  <header><slot name="header" /></header>
  <main><slot /></main>
  <aside><slot name="sidebar" /></aside>
</div>
<Layout>
  <Nav slot="header" />
  <UserMenu slot="sidebar" />
  <Article />   {/* goes to the default slot */}
</Layout>

Up Next

A first look at styles — and why they’re scoped by default.

Styling →