How to Use Props in Astro Components: Simple Guide
In Astro, you pass data to components using
props by defining them as parameters in the component's frontmatter script. You then access these props inside the component using the variable names you declared. This lets you customize component content dynamically.Syntax
In Astro components, props are declared as variables inside the frontmatter script block using export let. You pass values to these props when you use the component in another file by adding attributes with matching names.
- export let propName; declares a prop.
- <Component propName="value" /> passes a value to the prop.
- Inside the component, use
{propName}to access the prop value.
astro
--- export let title; --- <h1>{title}</h1>
Output
<h1>Your Title Here</h1>
Example
This example shows a simple Astro component named Greeting.astro that takes a name prop and displays a greeting message. The parent component passes the name prop when using <Greeting />.
astro
--- export let name; --- <p>Hello, {name}! Welcome to Astro.</p> --- <!-- Usage in a parent component --> <Greeting name="Alice" />
Output
<p>Hello, Alice! Welcome to Astro.</p>
Common Pitfalls
Common mistakes when using props in Astro include:
- Not declaring props with
export letinside the component frontmatter, so the prop is undefined. - Passing props with wrong attribute names or missing quotes for string values.
- Trying to mutate props inside the component, which is not allowed.
Always declare props explicitly and pass them correctly to avoid errors.
astro
--- // Wrong: missing export let declaration // Trying to use prop 'title' without declaring --- <h1>{title}</h1> --- // Correct way --- export let title; --- <h1>{title}</h1>
Quick Reference
Remember these key points when using props in Astro components:
- Declare props with
export let propName;in frontmatter. - Pass props as attributes when using the component.
- Access props inside JSX with
{propName}. - Props are read-only inside the component.
Key Takeaways
Declare props in Astro components using 'export let' in the frontmatter.
Pass props as attributes when using the component to customize content.
Access props inside the component with curly braces {propName}.
Props are read-only and should not be modified inside the component.
Always match prop names exactly between declaration and usage.