Astro JS - Islands



What is Astro Island?

In Astro framework, an island is an enhanced interactive UI component inside a static HTML page that can be hydrated on demand at client-side. The island reduces the JavaScript load at client-side and improves loading speed.

Island in astro can be of two types, client island or server island. A client island is an interactive JavaScript UI component that is hydrated separately from the rest of the page, while a server island is a UI component that server-renders its dynamic content separately from the rest of the page.

Island Components

Components are the building blocks of an Astro application. You can either declare a component as interactive island or a static HTML page. In the image below, you can see that we have a static HTML page with a client island component.

Astro Island Example

An island always runs in isolation from other islands on the page, and multiple islands can exist on a page. Client islands can still share state and communicate with each other, even though they run in different component contexts.

Create Client Island in Astro

An island in astro can be created using any other JavaScript framework like React, Vue, or Svelte. Astro is flexible enough to support all the major UI frameworks to create islands. The section below will show you how to create an island in Astro using React.

Step 1: Add React to Astro

First, you need to add React to your Astro project. Astro includes an astro add command to automate the setup of official integrations. Run the following command to add React to your Astro project:

>> npx astro add react

Step 2: Create a React Component

The code below, create a counter React component at 'src/' directory. The component will have a button that will increase the count by 1. This counter component will become an island of Astro page.

// File: src/components/Counter.jsx

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
        Count: {count}
    </button>
  );
}

Step 3: Use the Component in Astro Page

The code below defines an Astro page at 'src/pages/index.astro'. The page imports the Counter component and renders it in the page. The Counter component loads JavaScript only when it is visible in viewport, because we are using the 'client:visible' directive.

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

---
    import Welcome from '../components/Welcome.astro';
    import Layout from '../layouts/Layout.astro';
    import Counter from "../components/Counter.jsx";
---

<Layout>
    <Welcome />
    <h1>Welcome to Astro</h1>
    <p>This content is static.</p>
    
    <!-- Interactive Island -->
    <Counter client:visible />
</Layout>

Step 4: Output

The output shows astro page with a client island component. The counter component will increase the count by 1 when the button is clicked.

Astro JS Island Example
Advertisements