Understanding Astro Components
Components are the building blocks of any Astro application. They allow you to create reusable pieces of UI that can be used throughout your website.
What are Astro Components?
Astro components are files with a .astro extension that contain both the component logic and template. They use a special syntax that combines JavaScript and HTML-like markup.
Basic Component Structure
Here’s the basic structure of an Astro component:
---
// Component Script (JavaScript/TypeScript)
const greeting = "Hello, World!";
---
<!-- Component Template (HTML + Astro syntax) -->
<div>
<h1>{greeting}</h1>
<p>This is my first Astro component!</p>
</div>Component Script
The component script is written between the --- fences at the top of the file. This is where you can:
- Import other components or utilities
- Define variables and functions
- Fetch data
- Set up component props
---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';
const title = "My Awesome Page";
const items = ['Item 1', 'Item 2', 'Item 3'];
---Component Template
The template section uses HTML with Astro’s special syntax for dynamic content:
- Use
{expression}for JavaScript expressions - Use
{condition && <element>}for conditional rendering - Use
{array.map(item => <element>{item}</element>)}for lists
<Layout title={title}>
<main>
<h1>{title}</h1>
<ul>
{items.map(item => <li>{item}</li>)}
</ul>
</main>
</Layout>Props
Components can accept props to make them reusable:
---
export interface Props {
title: string;
description?: string;
}
const { title, description } = Astro.props;
---
<div class="card">
<h2>{title}</h2>
{description && <p>{description}</p>}
</div>Using Components
To use a component, import it in the script section and use it in the template:
---
import Card from '../components/Card.astro';
---
<Card title="My Card" description="This is a card component" />Best Practices
- Keep components small and focused: Each component should have a single responsibility
- Use descriptive names: Component names should clearly indicate their purpose
- Define TypeScript interfaces: Use TypeScript for better development experience
- Organize components: Group related components in folders
Components are fundamental to building maintainable Astro applications. In the next article, we’ll explore how to create layouts and organize your component structure!