Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Components and Islands

Props and Slots in Astro Components

Pass data into Astro components with props, type them with TypeScript, set defaults, spread attributes, use class:list and combine props with slots.

Components are how you stop repeating yourself. A button, a card, a pricing table or a navigation bar is written once and used everywhere. To make a component flexible you give it inputs. Astro has two kinds: props for data (strings, numbers, objects) and slots for chunks of markup.

You met both briefly in Layouts and slots. Here we go deeper and look at the typing, defaulting and styling helpers that make components pleasant to use.

Props

Attributes you write on a component tag arrive in Astro.props. Destructure them in the script:

ASTRO
---
// src/components/Card.astro
const { title, href } = Astro.props;
---
<article class="card">
  <h3><a href={href}>{title}</a></h3>
  <slot />
</article>
ASTRO
---
import Card from "../components/Card.astro";
---
<Card title="Learn Astro" href="/astro">
  <p>A guided course on building fast sites.</p>
</Card>

Notice that title and href are strings. To pass a non-string value, use braces: <Card count={3} featured={true} tags={["a", "b"]} />. A bare attribute such as <Card featured /> is treated as the boolean true.

Typing props

With TypeScript you declare an interface Props in the script, and Astro uses it to check every place the component is used. Editors then autocomplete the attributes and flag mistakes.

ASTRO
---
interface Props {
  title: string;
  href: string;
  level?: 2 | 3 | 4;
  tags?: string[];
}

const { title, href, level = 3, tags = [] } = Astro.props;
const Heading = `h${level}`;
---
<article>
  <Heading><a href={href}>{title}</a></Heading>
  <ul>{tags.map((tag) => <li>{tag}</li>)}</ul>
</article>

Three things happen here:

  • Optional props end with ? and receive defaults through destructuring.
  • A dynamic tag name works if the variable starts with a capital letter, so Heading renders <h3> or whichever level you chose.
  • Running astro check reports a missing title as a type error before you ship.

Props versus slots

Props Data: strings, numbers, objects
Slots Markup: children and regions
1 / 2

Spreading and rest props

When a wrapper component should pass unknown attributes to an inner element (such as id, aria-* or data-*), collect them with rest syntax and spread them:

ASTRO
---
// src/components/Button.astro
interface Props {
  variant?: "primary" | "ghost";
  [attribute: string]: unknown;
}
const { variant = "primary", class: className, ...rest } = Astro.props;
---
<button class:list={["btn", `btn-${variant}`, className]} {...rest}>
  <slot />
</button>
ASTRO
<Button variant="ghost" class="wide" type="submit" aria-label="Send">Send</Button>

The class attribute is renamed to className during destructuring because class is a reserved word in JavaScript.

class:list

class:list builds a class string from many shapes of input and drops falsy values. It accepts strings, arrays, objects (key = class, value = condition) and nested combinations:

ASTRO
---
const { active, size = "md" } = Astro.props;
---
<a class:list={["link", `link-${size}`, { active }, active && "bold"]} href="/">Home</a>

If active is true, the result is class="link link-md active bold". If not, the object entry and the && entry vanish. It replaces fiddly string concatenation.

Slots in more depth

A component can offer a default slot and several named ones. Inside the component you can also check whether a slot was filled using Astro.slots.has("name"), which lets you skip wrapper markup when nothing was provided:

ASTRO
---
const hasFooter = Astro.slots.has("footer");
---
<section class="panel">
  <div class="body"><slot /></div>
  {hasFooter && (
    <footer class="panel-footer"><slot name="footer" /></footer>
  )}
</section>

You can also render a slot to a string with await Astro.slots.render("name"), useful when a component needs to place the markup into an attribute or process it.

Passing a component as a prop

Props can be functions or components, which gives you flexible patterns. Remember that the value must be a capitalized variable when used as a tag:

ASTRO
---
const { icon: Icon, label } = Astro.props;
---
<span>{Icon && <Icon />} {label}</span>

Stand-in: props with defaults and class:list

The next stand-in implements the helper functions that Astro supplies: default props, rest props and class:list. Watch how falsy values disappear.

Node.js Stand-in: class:list and prop defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: slot checks and fallbacks

A panel that hides its footer wrapper when no footer content is given is a good example of Astro.slots.has. Here it is as a plain function.

Node.js Stand-in: optional slot regions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Design guidance

  • Prefer few, well-named props. If a component needs ten, it probably does too much.
  • Use union types ("primary" | "ghost") instead of free strings for variants.
  • Give every optional prop a default in destructuring so the template never sees undefined by accident.
  • Do not mutate props. Treat Astro.props as read-only input.
  • Use slots when callers need to supply markup, and props when they supply values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the attributes passed to an Astro component?

    Props arrive in Astro.props. Destructure them in the component script.
  2. 2. What does class:list={['a', { b: false, c: true }]} produce?

    Object entries are included only when their value is truthy, so b is dropped.
  3. 3. How can a component skip a wrapper when no footer slot content was passed?

    Astro.slots.has returns true only when the caller supplied content for that slot.
  4. 4. Why is class renamed during destructuring (class: className)?

    You cannot declare a variable named class, so you rename it and then pass it to class:list.

Summary

  • Attributes on a component tag become Astro.props; use braces for non-string values.
  • Declare interface Props for type checking and use destructuring defaults for optional props.
  • Collect extra attributes with rest props and spread them onto the inner element.
  • class:list combines strings, arrays and conditional objects into one class string.
  • Slots carry markup; Astro.slots.has() lets a component adapt when a slot is empty.

Next: Client-Side Scripts