0
0
AstroHow-ToBeginner ยท 3 min read

How to Create a Component in Astro: Simple Guide

In Astro, create a component by making a new .astro file with HTML and optional JavaScript inside. Use export let to accept props, then import and use the component in other pages or components with <ComponentName /> syntax.
๐Ÿ“

Syntax

To create a component in Astro, you write a .astro file that contains HTML markup and optional JavaScript. Use export let to define properties (props) that the component can receive from its parent. Then you can use the component by importing it and placing it as a tag in your page or another component.

  • export let propName; declares a prop.
  • HTML inside the file is the component's template.
  • Use <ComponentName /> to include the component.
astro
---
export let title;
---

<h1>{title}</h1>
<p>This is a simple Astro component.</p>
๐Ÿ’ป

Example

This example shows a component named Greeting.astro that takes a name prop and displays a greeting message. Then it is used in a page to show the greeting.

astro
---
export let name;
---

<h2>Hello, {name}!</h2>


---
import Greeting from './Greeting.astro';
---

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Astro Component Example</title>
  </head>
  <body>
    <Greeting name="Alice" />
  </body>
</html>
Output
<h2>Hello, Alice!</h2>
โš ๏ธ

Common Pitfalls

Beginners often forget to use export let to declare props, so the component won't receive data. Another mistake is not importing the component before using it, which causes errors. Also, using uppercase names for components is important because Astro treats lowercase tags as HTML elements.

astro
---
let name;
---
<h2>Hello, {name}!</h2>

---
export let name;
---
<h2>Hello, {name}!</h2>
๐Ÿ“Š

Quick Reference

  • Create a component as a .astro file.
  • Use export let propName; to accept props.
  • Import components with import Component from './Component.astro';.
  • Use components with <Component propName="value" />.
  • Component names must start with uppercase letters.
โœ…

Key Takeaways

Create components in Astro by making .astro files with HTML and optional props.
Declare props using export let to pass data into components.
Import and use components with uppercase names as custom tags.
Always import components before using them to avoid errors.
Component files combine markup and logic in one place for easy reuse.