Props
Props (short for properties) are the data a component receives from outside, through the attributes of its tag. Thanks to them one post card component can show any post: the page passes it the title and the date.
Receiving props
Inside a component the props are in the Astro.props object. Create src/components/PostCard.astro:
---
const { title, url } = Astro.props;
---
<article>
<h2><a href={url}>{title}</a></h2>
</article>The component takes two values out of Astro.props with destructuring and renders a link with the post title.
Passing props
Values are passed as attributes, like in HTML. Open src/pages/posts/index.astro (create it if it does not exist yet):
---
import PostCard from '../../components/PostCard.astro';
---
<h1>Posts</h1>
<PostCard title="First post" url="/posts/first-post" />
<PostCard title="How I learn Astro" url="/posts/learning-astro" />Open http://localhost:4321/posts and two cards with links appear. Strings are passed in quotes, everything else (numbers, arrays, objects, variables) in curly braces: count={3}, tags={['astro', 'css']}.
Props type
If you describe a Props interface in the frontmatter, the editor suggests names and checks types. Update src/components/PostCard.astro:
---
interface Props {
title: string;
url: string;
date?: Date;
}
const { title, url, date } = Astro.props;
---
<article>
<h2><a href={url}>{title}</a></h2>
{date && <time datetime={date.toISOString()}>{date.toLocaleDateString('en-US')}</time>}
</article>The question mark makes date optional. If you forget to pass title, the editor underlines the tag and the npx astro check command prints an error in the terminal.
Default values
A default value is set right in the destructuring:
---
interface Props {
title: string;
url: string;
label?: string;
}
const { title, url, label = 'Read' } = Astro.props;
---
<article>
<h2>{title}</h2>
<a href={url}>{label}</a>
</article>A card without a label attribute shows the link "Read", and label="More" replaces the text.
Common mistake
A number is passed in quotes: count="3". The component receives the string "3", and count + 1 gives "31" instead of 4. Pass everything that is not a string in curly braces: count={3}.