Astro Props
You might be familiar with the concept of props from a modern JavaScript framework like React, or Vue or Svelte.
NOTE: I wrote about all of those in the past, and you can find my articles on React Props, Vue Props and Svelte Props.
Props are the way we can pass information to components. This includes variables, but also functions.
Astro components also support props.
Here’s how to use them.
Suppose you define a Hello component in src/components/Hello.astro:
<p>Hello!</p>You can pass a name prop to the component when you use it, like this: <Hello name="Flavio" />, and you can display the name in your component output by using this syntax:
<p>Hello {Astro.props.name}!</p>It’s common to extract the props to individual variables with object destructuring in the component’s frontmatter section, which is nice when you have complex components:
---
const { name } = Astro.props
---
<p>Hello {name}!</p>Here’s how to work with multiple props, to support for example this usage: <Hello name="Flavio" message="Welcome" />
---
const { name, message } = Astro.props
---
<p>{message} {name}!</p>And in this way you can support defaults for props that might be unset:
---
const { name = '', message = 'Hello' } = Astro.props
---
<p>{message} {name}!</p>download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.