Astro Introduction Guide For Beginners

Learn how to create efficient and fast websites with Astro, the web framework for content-driven websites

Astro Introduction Guide For Beginners

September 1, 2024

Astro HTML CSS JavaScript React

Table of Contents

  1. Introduction
  2. Astro Islands
  3. API Endpoints
  4. Build and Preview the Project
  5. Conclusion
  6. References

Chapter 1: Introduction

What is Astro?

Astro is a an open-source web framework, is very customizable and it’s built with performance in mind. It’s a great tool for building static sites, blogs, and even dynamic web applications.

Init a new Astro project

To create a new Astro project, you can use the following command:

Terminal window
npm create astro@latest

Some questions will be asked, after that, the project will be created. You can follow the example below:

npx create-vite

Structure of an Astro project

An Astro new project has the following structure:

Terminal window
.
β”œβ”€β”€ README.md
β”œβ”€β”€ astro.config.mjs
β”œβ”€β”€ package-lock.json
β”œβ”€β”€ package.json
β”œβ”€β”€ public
β”‚ └── favicon.svg
β”œβ”€β”€ src
β”‚ β”œβ”€β”€ components
β”‚ β”‚ └── Card.astro
β”‚ β”œβ”€β”€ env.d.ts
β”‚ β”œβ”€β”€ layouts
β”‚ β”‚ └── Layout.astro
β”‚ └── pages
β”‚ └── index.astro
└── tsconfig.json

Layout

Astro uses a layout system to define the structure of the pages. It can be re-used in other parts of application, where a developer wants to use the same page layout.

---
interface Props {
title: string;
}
const { title } = Astro.props;
---
<!-- src/layouts/Layout.astro -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Astro description" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
</head>
<body>
<slot />
</body>
</html>
<style is:global>
:root {
--accent: 136, 58, 234;
--accent-light: 224, 204, 250;
--accent-dark: 49, 10, 101;
--accent-gradient: linear-gradient(
45deg,
rgb(var(--accent)),
rgb(var(--accent-light)) 30%,
white 60%
);
}
html {
font-family: system-ui, sans-serif;
background: #13151a;
}
code {
font-family:
Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu Sans Mono,
Bitstream Vera Sans Mono,
Courier New,
monospace;
}
</style>

Let’s see some elements that we can find:

Pages

Astro uses the .astro extension for its components. The pages are the main components of the application, they are the ones that will be rendered in the browser.

Replace the content of the index.astro file with the following code:

---
import Layout from "./layouts/Layout.astro";
---
<!-- src/pages/index.astro -->
<Layout title="Astro Guide">
<h1>Welcome to Astro Introduction Guide For Beginners</h1>
<p>Learn how to create efficient and fast websites with Astro.</p>
</Layout>
<style>
h1 {
color: rgb(var(--accent));
}
p {
color: white;
}
</style>

Run the project

To test the project, you can use the following command (using the terminal):

Terminal window
npm run dev

Your terminal will show the following message:

alt text

The project will be running on http://localhost:4321.

Components

Components allow us to split the UI into independent and reusable pieces of code. They can be used in different parts of the application.

Change the content of the Card.astro file with the following code:

---
interface Props {
title: string;
description: string;
}
const { title, description } = Astro.props;
---
<!-- src/components/Card.astro -->
<article>
<h2>{title}</h2>
<p>{description}</p>
</article>
<style>
article {
background: rgb(var(--accent-light));
padding: 1rem;
border-radius: 0.5rem;
margin: 1rem 0;
}
h2 {
color: rgb(var(--accent));
}
p {
color: rgb(var(--accent-dark));
}
</style>

We can define the props that the component will receive, in this case, the Card component will receive a title and a description. The values of the props are extracted from the Astro.props object.

You can render the props in the component using curly braces {}.

If you want to use the Card component in the index.astro file, you can import it and use it like this:

---
import Layout from "./layouts/Layout.astro";
import Card from "./components/Card.astro";
---
<!-- src/pages/index.astro -->
<Layout title="Astro Guide">
<h1>Welcome to Astro Guide For Beginners</h1>
<p>This is a guide to learn how to use Astro.</p>
<Card title="Card Title" description="Card Description" />
</Layout>
<style>
h1 {
color: rgb(var(--accent));
}
p {
color: white;
}
</style>

Routing

Astro uses the file system to define the routes of the application.

For example, if you want to create a new page called about.astro, you can create a new file in the src/pages directory called about.astro:

---
import Layout from "./layouts/Layout.astro";
---
<!-- src/pages/about.astro -->
<Layout title="About">
<h1>About</h1>
<p>This is the about page.</p>
<a href="/">Go back home</a>
</Layout>
<style>
h1 {
color: rgb(var(--accent));
}
p {
color: white;
}
</style>

The about.astro file will be available at http://localhost:4321/about.

To go back to the home page, you can use the <a href="/">Go back home</a> tag.

Chapter 2: Astro Islans

What is Astro Islands?

An interactive UI component. Multiple islands can exist on a page, and each island can use any UI framework, or even just plain Astro code.

Using React with Astro

The Astro integrations are very easy to install and use. For integrate React with Astro, you can use the following command:

Terminal window
npx astro add react

The terminal will show the following messages:

alt text

Run the project again:

Terminal window
npm run dev

Next, create the file ReactComponent.jsx in the src/components directory and after that, add the following react component to the file:

src/components/ReactComponent.jsx
const Hello = () => {
return <h1 style={{ color: "green" }}>Hello from React!</h1>;
};
export default Hello;

Next you can import the new React component in the index.astro file:

---
import Layout from "./layouts/Layout.astro";
import Card from "./components/Card.astro";
import ReactComponent from "./components/ReactComponent.jsx";
---
<!-- src/pages/index.astro -->
<Layout title="Astro Guide">
<h1>Welcome to Astro Guide For Beginners</h1>
<p>This is a guide to learn how to use Astro.</p>
<Card title="Card Title" description="Card Description" />
<ReactComponent client:load/>
</Layout>
<style>
h1 {
color: rgb(var(--accent));
}
p {
color: white;
}
</style>

Add the client:load attribute to the React component to make sure it’s only rendered on the client side.

Chapter 3: API Endpoints

What is Astro Endpoints?

Are custom endpoints to serve any type of data to the client. They can be used to fetch data from a database, an external API, or any other source.

Using Astro Endpoints

You will need to create a new file in the src/pages/api directory. Next, create a file called data.json.ts and add the following code:

src/pages/api/data.json.ts
export async function GET() {
return new Response(
JSON.stringify({
message: "Hello from the API!"
})
)
}

You can consume the data from the endpoint in the ReactComponent.jsx file that we created earlier:

Replace the content of the ReactComponent.jsx file with the following code:

src/components/ReactComponent.jsx
import { useEffect, useState } from "react";
const Hello = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch("/api/data.json")
.then((res) => res.json())
.then((data) => {
setData(data);
});
}, []);
return (
<>
<h1 style={{ color: "green" }}>Hello from React!</h1>;
<p style={{ color: "yellow" }}>{data ? data.message : "Loading..."}</p>
</>
)
};
export default Hello;

If you want to see in the browser the message from the API, check the url http://localhost:4321/api/data.json, the data will be displayed using json format. This is beacuse in the name of the file we have the .json extension to indicate the response format.

Build and Preview the Project

To build the project, for production, you can use the following command:

Terminal window
npm run build

This command will generate a dist directory with the production build of the project.

Inside the dist directory, you can see multiple static files inlcuding the index.html file and the other pages. If you check the API folder you will see the data.json file with the data that we created.

alt text

Next, stop the development server using Ctrl + C and run the following command:

Terminal window
npm run preview

This command will start a local server similar to the npm run dev command (in the same port), but it will serve the production build of the project.

Conclusion

Astro is a very complete technology, we have a very simple routing system for beginners, and the syntax is incredibly simple!

I hope you found this guide useful, that you can start using Astro in your projects and that you can go deeper into more advanced topics.

If you have any questions, feel free to ask via social media.

Happy coding!

References