/

Astro Props: Passing Information to Components

Astro Props: Passing Information to Components

If you’ve worked with modern JavaScript frameworks like React, Vue, or Svelte, you’re probably familiar with the concept of props. Props allow us to pass information, including variables and functions, to components. The good news is that Astro components also support props. Let’s see how to use them effectively.

First, let’s say you have a Hello component defined in src/components/Hello.astro:

1
<p>Hello!</p>

To pass a name prop to the component when using it, you can do <Hello name="Flavio" />. To display the name in the component’s output, you can use the following syntax:

1
<p>Hello {Astro.props.name}!</p>

Often, it’s useful to extract props into individual variables using object destructuring in the component’s frontmatter section, especially for complex components. Here’s an example:

1
2
3
4
---
const { name } = Astro.props
---
<p>Hello {name}!</p>

Now, let’s talk about working with multiple props. You might want to support a usage like <Hello name="Flavio" message="Welcome" />. To achieve this, you can do the following:

1
2
3
4
---
const { name, message } = Astro.props
---
<p>{message} {name}!</p>

Finally, you can provide default values for props that might be unset. Here’s how:

1
2
3
4
---
const { name = '', message = 'Hello' } = Astro.props
---
<p>{message} {name}!</p>

By following these guidelines, you can effectively use props in Astro and create more flexible and reusable components for your projects.

Tags: Astro Props, JavaScript, Frontend Development, Component-Based Architecture