.astro files) are the foundation of any Astro project. They are HTML-only templating components with no client-side runtime.
Component Structure
An Astro component consists of two main parts: the component script (JavaScript/TypeScript) and the component template (HTML).The component script is enclosed in code fences (
---) and runs during the build. This code never reaches the browser.Component Script
The component script runs at build time on the server. You can:- Import other components
- Import data from other files
- Fetch data from APIs or databases
- Create variables to use in your template
src/components/BlogPost.astro
Everything in the component script runs once at build time, not on every request.
Props
Components accept data through props, similar to React or Vue:src/components/Card.astro
TypeScript Props
Define prop types with TypeScript:src/components/Card.astro
- Basic Props
- Typed Props
- Default Values
Slots
Slots allow you to pass child content to components:src/components/Card.astro
Named Slots
Define multiple slots with names:src/components/BlogPost.astro
Fallback Content
Provide default content if no slot content is passed:Slot Implementation
From the source code atsrc/runtime/server/render/slot.ts, slots are rendered as functions that return template results:
The Astro Global
Every Astro component has access to the globalAstro object:
- Common Properties
- Utilities
Framework Components
Astro components can render framework components from React, Vue, Svelte, and more:Component Rendering
Fromsrc/runtime/server/render/component.ts, Astro determines how to render each component:
Practical Examples
Reusable Button Component
src/components/Button.astro
Data-Fetching Component
src/components/UserProfile.astro
Conditional Rendering
src/components/Alert.astro
Best Practices
1
Keep components focused
Each component should have a single responsibility.
2
Use TypeScript
Type your props for better developer experience and fewer bugs.
3
Extract reusable logic
Move complex logic to utility functions in the component script.
4
Use slots for flexibility
Slots make components more reusable and composable.
5
Default to Astro components
Only use framework components when you need client-side interactivity.
Learn More
Islands Architecture
Add interactivity with client directives
Layouts
Create reusable page structures