Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: A Portfolio Site with Interactive Islands

Build a fast Astro portfolio: project cards, a filter island, a no-flash theme toggle, a contact form with an action and optimised images.

A portfolio is the perfect islands project: 95 percent static content (about, projects, contact), and three small interactive bits. In this project you plan the page by asking, for every piece, "does it really need JavaScript?", then build the three islands that do.

The plan

Piece Interactive? Approach
Header, hero, about No Astro components
Project grid Yes (filter by tag) Small island, client:visible
Theme toggle (light/dark) Yes Inline script, no framework
Contact form Yes (submit) Astro Action with a no-JS fallback
Footer No Astro component
flowchart TB
  P["index.astro (static HTML)"] --> H["Hero, About (no JS)"]
  P --> G["ProjectGrid island<br/>client:visible"]
  P --> T["Theme toggle<br/>inline script"]
  P --> C["Contact form<br/>Astro Action"]

Only three parts ship JavaScript; everything else is plain HTML.

Step 1: Project data in a collection

TypeScript
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { file } from 'astro/loaders';

const projects = defineCollection({
  loader: file('src/data/projects.json'),
  schema: ({ image }) =>
    z.object({
      title: z.string(),
      summary: z.string(),
      tags: z.array(z.enum(['web', 'cli', 'mobile', 'data'])),
      url: z.string().url().optional(),
      cover: image(),
      coverAlt: z.string(),
    }),
});
export const collections = { projects };
JSON
[
  { "id": "weather-cli", "title": "Weather CLI", "summary": "Forecast in your terminal.", "tags": ["cli"], "cover": "../assets/weather.png", "coverAlt": "Terminal showing a forecast" }
]

Step 2: The static page with optimised images

ASTRO
---
import { getCollection } from 'astro:content';
import ProjectGrid from '../components/ProjectGrid.jsx';
import { getImage } from 'astro:assets';

const entries = await getCollection('projects');
const projects = await Promise.all(
  entries.map(async ({ id, data }) => {
    const img = await getImage({ src: data.cover, width: 480, format: 'webp' });
    return { id, ...data, cover: undefined, image: img.src, width: img.attributes.width, height: img.attributes.height };
  }),
);
---
<section id="projects">
  <h2>Projects</h2>
  <ProjectGrid client:visible projects={projects} />
</section>

Props are plain serialisable objects, so they cross the island boundary. The grid is below the fold, so client:visible defers its JavaScript until the visitor scrolls to it. Because Astro renders it to HTML first, search engines and no-JS users still see every project.

Step 3: The filter island

JSX
// src/components/ProjectGrid.jsx
import { useState, useMemo } from 'react';

export default function ProjectGrid({ projects }) {
  const [tag, setTag] = useState('all');
  const tags = useMemo(() => ['all', ...new Set(projects.flatMap((p) => p.tags))], [projects]);
  const visible = tag === 'all' ? projects : projects.filter((p) => p.tags.includes(tag));

  return (
    <>
      <div role="group" aria-label="Filter projects">
        {tags.map((t) => (
          <button key={t} aria-pressed={t === tag} onClick={() => setTag(t)}>{t}</button>
        ))}
      </div>
      <ul className="grid">
        {visible.map((p) => (
          <li key={p.id}>
            <img src={p.image} width={p.width} height={p.height} alt={p.coverAlt} loading="lazy" />
            <h3>{p.title}</h3>
            <p>{p.summary}</p>
          </li>
        ))}
      </ul>
    </>
  );
}

aria-pressed tells screen readers which filter is active.

Step 4: Theme toggle without a flash

Dark mode must be set before the first paint, or users see a white flash. Put a tiny inline script in the <head> and a small click handler in the body:

ASTRO
<head>
  <script is:inline>
    const saved = localStorage.getItem('theme');
    const dark = saved ? saved === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
    document.documentElement.classList.toggle('dark', dark);
  </script>
</head>
<body>
  <button id="theme" aria-label="Toggle dark mode">Theme</button>
  <script>
    document.getElementById('theme')?.addEventListener('click', () => {
      const dark = document.documentElement.classList.toggle('dark');
      localStorage.setItem('theme', dark ? 'dark' : 'light');
    });
  </script>
</body>

No framework, about 300 bytes. If you use <ClientRouter />, repeat the class logic in an astro:after-swap listener.

Step 5: Contact form with an Action

TypeScript
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro:schema';

export const server = {
  contact: defineAction({
    accept: 'form',
    input: z.object({
      name: z.string().min(2),
      email: z.string().email(),
      message: z.string().min(10).max(2000),
      company: z.string().max(0).optional(), // honeypot
    }),
    handler: async ({ name, email, message }) => {
      const res = await fetch('https://mail.example.com/send', {
        method: 'POST',
        headers: { authorization: `Bearer ${import.meta.env.MAIL_TOKEN}` },
        body: JSON.stringify({ name, email, message }),
      });
      if (!res.ok) throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'Could not send. Try again later.' });
      return { sent: true };
    },
  }),
};

The page uses <form method="POST" action={actions.contact}> plus Astro.getActionResult(actions.contact) as in the Actions lesson, so it works with JavaScript disabled. The hidden company field is a honeypot: humans leave it empty, many bots fill it. Add rate limiting at the platform level for real use.

Step 6: Polish and checks

  • <title> and description per page; Open Graph image from getImage().
  • Contrast and focus styles checked; every image has useful alt.
  • Run Lighthouse in mobile mode: expect near-perfect scores because most of the page is static.
  • Deploy to a static host plus an adapter only if the form action needs one.

Try it: the filter logic

The filter island's logic, including the derived tag list, runnable without React.

JS Project filter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: validate and sanitise the contact form

The action's checks as plain JavaScript, including the honeypot and header-injection guard.

JS Contact form validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the project grid hydrated with client:visible?

    client:visible delays loading and hydrating the island, while the server-rendered HTML is already visible and indexable.
  2. 2. Why is the theme script inline in the head?

    A blocking inline script runs before the page paints, so the right theme is applied immediately.
  3. 3. What is a honeypot field?

    A filled honeypot signals automated submission, so the handler can ignore the message.
  4. 4. Which pieces of the portfolio should stay plain Astro components?

    Content with no interaction needs no JavaScript, which is the point of islands.

Summary

  • Decide per piece whether JavaScript is needed; build only those parts as islands.
  • Project data lives in a collection; images pass through getImage().
  • A small inline head script prevents theme flashes.
  • The contact form is an Action with validation, a honeypot and a no-JS fallback.

Next: Project: A Documentation Site with Search