In the previous lesson we’ve seen our first Astro site and I introduced components.
Let’s now talk more about them.
In their simplest form, components can just be some HTML tags, for example
<p>test</p>
Create a src/components/Test.astro
file with that content, and import that in a page component, then add it to the component markup as you would write an HTML tag, like this
<Test />
See, the markup now appears in the page:
The syntax:
<Test />
was borrowed from JSX, a “templating language” introduced by React.
TIP: If you already know JSX, in Astro components the syntax is a little different, because for example we can have siblings in a tree (no need for fragment or
<>
) and no need to useclassName=
to add HTML classes, justclass=
.
Components can add JavaScript variables in their “frontmatter”, and you can use them in the HTML markup:
---
const test = 'hello'
---
<p>{test}</p>
Let’s now talk about props.
Astro components accept props.
This means you can pass values to a component from a parent component.
For example we can pass a name
attribute to the Test component like this:
<Test name="joe" />
Inside the Test component we can use this value by adding this to the component frontmatter:
---
const { name } = Astro.props
---
<p>test</p>
And now we can use it in the markup, using a special JSX-like syntax that lets us embed JavaScript inside the HTML:
---
const { name } = Astro.props
---
<p>test {name}</p>
Here’s the result:
And this is how we can embed data in Astro components.
If you had an array, you could print all items in the array using this syntax:
---
const list = [1, 2, 3, 4]
---
<p>Some numbers:</p>
<ul>
{list.map(n => <li>{n}</li>)}
</ul>