Astro JS - Components



Astro Components

Astro components are the building blocks of an Astro application. They are similar to React components, but with a few key differences. They are HTML-only templating components with no client-side runtime and use the .astro file extension. Astro components are designed to be fast, lightweight, and easy to use.

Key Features of Astro Components

  • Ships zero client-side JavaScript by default.
  • Components can be reusable UI elements, like a header or a profile card.
  • Astro components render HTML either at build-time or on-demand.
  • JavaScript can be included in the component frontmatter, which will be striped off from final page sent to user, resulting in fast loading time.

Structure of Astro Component

An astro component is made of two parts, component script and component template. The component script is written in frontmatter of the component file, and the component template is written in the body of the component file. The file will be stored with .astro extension.

<!-- File: /src/pages/header.astro -->

---
<!-- Component Script (JavaScript) -->
---

<!-- Component Template (HTML + JS Expressions) -->

Example of Astro Component

Here is an example of an Astro component that displays a header with a title and a navigation menu.

<!-- File: /src/pages/header.astro -->

---
const title = "Header Component";
---
<header>
    <h1>{title}</h1>
    <nav>
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
            <li><a href="/contact">Contact</a></li>
        </ul>
    </nav>

Output

The above code will render a header with a title and a navigation menu.

Astro Component Example

The Component Script

As explained in the above structure, Astro uses fences (---) to identify the component script in your Astro component. This is a similar concept of Markdown and it is called as frontmatter. You can use the component script to write any JavaScript code that you need to render your template. This can include:

  • importing other Astro components
  • importing other framework components, like React
  • importing data, like a JSON file
  • fetching content from an API or database
  • creating variables that you will reference in your template

Example

Here is an example of a component script that imports an Astro component, a React component, and fetches data from a JSON file.

---
import AstroComponent from '/AstroComponent.astro';
import ReactComponent from '/ReactComponent.jsx';
import Data from '../data/pokemon.json';

// Access passed-in component props
const { title } = Astro.props;

// Fetch external data, even from a private API or database
const data = await fetch('SOME_SECRET_API_URL/users').then(r => r.json());
---
<!-- Your template here! -->

The code fence will ensure that the no JavaScript code will be shipped to the client-side. It won't escape to frontend and fall to user's hand, which means you can even add expensive or sensitive (like a call to your private database) code in your component script.

The Component Template

The component template is the code below fence (---) in the astro component, and it will determine the HTML structure of your component. If you write plain HTML here, your component will render that HTML in any Astro page it is imported and used. The Astro's template syntax also supports JavaScript expressions, which can be used to render dynamic content. Data and values defined in the component script can be used in the component template to produce dynamically-created HTML.

Example

Here is an example of a component template that uses JavaScript expressions to render dynamic content.

---
const title = "Header Component";
const Data = [
    { id: 1, name: "Bulbasaur" },
    { id: 2, name: "Ivysaur" },
    { id: 3, name: "Venusaur" }
];
---

<header>
    <h1>{title}</h1>
    <nav>
        <ul>
            {Data.map(pokemon => (
                <li key={pokemon.id}>
                    <a href={`/pokemon/${pokemon.id}`}>{pokemon.name}</a>
                </li>
            ))}
        </ul>
    </nav>

Component Props

An Astro component can define and accept props. These props then become available to the component template for rendering HTML. Props are available on the Astro.props global in your frontmatter script.

Example

Here is an example of a component that receives a greeting prop and a name prop. Notice that the props to be received are destructured from the global Astro.props object.

---
// Usage: <GreetingHeadline greeting="Howdy" name="Partner" />
const { greeting, name } = Astro.props;
---

<h2>{greeting}, {name}!</h2>

This component, when imported and rendered in other Astro components, layouts or pages, can pass these props as attributes:

---
import GreetingHeadline from './GreetingHeadline.astro';
const name = 'Tutorialspoint';
---
<h1>Greeting Card</h1>
<GreetingHeadline greeting="Hi" name={name} />
<p>I hope you have a wonderful day!</p>
Advertisements