Using React Components in Astro

#astro#react#islands

Astro Islands

Sometimes you need interactivity. Astro islands allow you to mount React components into your static HTML.

// src/components/Counter.tsx
import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <button 
      onClick={() => setCount(c => c + 1)}
      className="px-4 py-2 bg-blue-600 text-white rounded"
    >
      Count: {count}
    </button>
  );
}

Usage in Astro

Hydrate it with client:load or client:visible.

---
import Counter from '../components/Counter';
---

<Counter client:visible />

This ensures the JavaScript only loads when the user scrolls the component into view.