Components & styles · Lesson 4 of 22 · 10 min

Your first component: the Header

Pull markup into a reusable component and pass it data with props.

A component is just an .astro file you import into another file. Every page on the site needs the same header, so it’s the perfect first component.

1. Create the component

Make a new folder src/components/ and add Header.astro:

src/components/Header.astro

---
interface Props {
  siteName: string;
}

const { siteName } = Astro.props;
---

<header>
  <div class="container inner">
    <a href="/" class="logo">{siteName}</a>
  </div>
</header>

What’s happening

  • interface Props describes what data this component accepts. It’s TypeScript, and it’s optional, but it gives you autocomplete and catches typos.
  • Astro.props holds whatever the parent passed in.
  • The container and inner classes will get styles in lesson 6.

2. Use it on the homepage

Import the component at the top of index.astro, then use it like an HTML tag:

src/pages/index.astro

---
import Header from '../components/Header.astro';

const businessName = 'Sunday Supper Co.';
const tagline = 'Seasonal home cooking for your table.';
const dishes = ['Charred corn', 'Pinto beans', 'Peach cobbler'];
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{businessName}</title>
  </head>
  <body>
    <Header siteName={businessName} />

    <h1>{tagline}</h1>
    <ul>
      {dishes.map((dish) => <li>{dish}</li>)}
    </ul>
  </body>
</html>

siteName={businessName} passes the value in. Plain strings work too: <Header siteName="Sunday Supper Co." />.

Rules worth knowing

  • Component names start with a capital letter. <Header /> is a component, <header> is HTML.
  • Paths are relative to the current file. From src/pages/, the components folder is ../components/.
  • Props can be anything: strings, numbers, arrays, objects, even other data you imported.

Optional props and defaults

Add a ? to make a prop optional, and give it a default when you destructure:

---
interface Props {
  siteName: string;
  tagline?: string;
}

const { siteName, tagline = 'Good food, close to home' } = Astro.props;
---