0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/.changeset/rich-starfishes-begin.md
Nate Moore a136c85e6b
New Props API (#515)
* wip: update props api

* feat(#139, #309): enable new props api

* chore: migrate examples to new props API

* docs: update syntax guide for new props API

* chore: update examples to new props API

* chore: update docs to new Props API

* fix: hide __astroInternal from `Astro.props` consumers

* chore: remove scratchpad file

* chore: fix script error

* test: fix failing collection tests

* fix: set __astroInternal to `enumerable: false`

* chore: add changeset

* feat: warn users using old props api
2021-06-24 17:48:24 -05:00

1.8 KiB

astro
minor

This is a breaking change!

Astro props are now accessed from the Astro.props global. This change is meant to make prop definitions more ergonomic, leaning into JavaScript patterns you already know (destructuring and defaults). Astro components previously used a prop syntax borrowed from Svelte, but it became clear that this was pretty confusing for most users.

 ---
+ const { text = 'Hello world!' } = Astro.props;
- export let text = 'Hello world!';
 ---

 <div>{text}</div>

Read more about the .astro syntax


How do I define what props my component accepts?

Astro frontmatter scripts are TypeScript! Because of this, we can leverage TypeScript types to define the shape of your props.

---
export interface Props {
  text?: string;
}
const { text = 'Hello world!' } = Astro.props as Props;
---

Note

Casting Astro.props as Props is a temporary workaround. We expect our Language Server to handle this automatically soon!

How do I access props I haven't explicitly defined?

One of the great things about this change is that it's straight-forward to access any props. Just use ...props!

---
export interface Props {
  text?: string;
  [attr: string]: unknown;
}
const { text = 'Hello world!', ...props } = Astro.props as Props;
---

What about prop validation?

We considered building prop validation into Astro, but decided to leave that implementation up to you! This way, you can use any set of tools you like.

---
const { text = 'Hello world!' } = Astro.props;

if (typeof text !== 'string') throw new Error(`Expected "text" to be of type "string" but recieved "${typeof string}"!`);
---