Basics

  • Astro is like HTML with strong JavaScript support. It is most comparable to JSX syntax.
  • Any file JavaScript should be in code fences --- js goes here --- at the beginning of the file. This is the frontmatter script of the file.
  • Other expressions can go in braces throughout the file, e.g. {pageTitle} or {isStudent && <p>Still studying!</p>}.
  • Astro <style> tags are more flexible and scoped (by default).
  • In order for the style tag to use a variable from the front matter script, you must define them like <style define:vars={{skillColor}}> </style>
    • To use them, use var(--skillColor)
  • You can use js using a <script> element and either write the code or import "../scripts/menu.js";

Global Stylesheet

Make a stylesheet in a reasonably accessible location and import the stylesheet into pages that you want to use it.
import '../styles/global.css';

In the case of conflicting style sheets, the local one will take precedence.

Components

Reusable elements like navigation, footers, buttons, etc. They take the form of HTML elements, sort of like React.

How to use

  1. Create an astro file in components that is the name of your components
  2. Write some astro
  3. Import the component into the file you want to use it in like import Navigation from '../components/Navigation.astro';

How to dynamically customize components

With props (…just like React)

  1. Create your component
  2. In the frontmatter of the component, create a const like so const { platform, username } = Astro.props;. The braces perform object destructuring which grab the properties contained in the “object of properties” passed in with the component.
  3. In an instance of your component, be sure to specify the “props” in the element tag like so <Social platform="twitter" username="astrodotbuild" />

Layouts

Let this be BaseLayout.astro, notice the <slot />.

---
const { pageTitle } = Astro.props;
---
<html>
  <body>
    <Header />
    <slot />
    <Footer />
  </body>
</html>

Anything that imports this layout and uses it as an element, it’s child content will be injected into <slot />.
Let this be index.astro, notice how it also supports props.

---
import BaseLayout from '../layouts/BaseLayout.astro';
const pageTitle = "Home Page";
---
<BaseLayout pageTitle={pageTitle}>
  <h2>My awesome blog subtitle</h2>
</BaseLayout>

Realistically, this just seems like the same thing as a component with the addition of nesting/inserting HTML.

Markdown

Turns out you can read the frontmatter from markdown just as well and use it with your props. Just make sure to grab const { frontmatter } = Astro.props; which gives you a dictionary where you can grab frontmatter.author and so on.

Astro Islands

Add frontend framework components in with npx astro add <name>. This effectively allows you to use components from other frameworks entirely. That means those components will be written in that framework, not in a .astro file.