0
0
Astroframework~5 mins

React components in Astro

Choose your learning style9 modes available
Introduction

React components let you build interactive parts of a website. Using them in Astro helps combine React's power with Astro's fast page loading.

You want to add a button that changes when clicked inside an Astro page.
You need a form with live validation inside an Astro site.
You want to reuse a React-built widget in an Astro project.
You want to mix static content with dynamic React parts for better performance.
Syntax
Astro
import ReactComponent from './Component.jsx';

---

<ReactComponent client:load />

Use client:load to load React components on the client side after the page loads.

You can also use client:idle, client:visible, or client:media for different loading strategies.

Examples
This loads the MyButton React component when the page loads.
Astro
import MyButton from './MyButton.jsx';

---

<MyButton client:load />
This loads the Counter React component only when it becomes visible on the screen.
Astro
import Counter from './Counter.jsx';

---

<Counter client:visible />
This loads the Widget React component when the browser is idle, improving performance.
Astro
import Widget from './Widget.jsx';

---

<Widget client:idle />
Sample Program

This example shows a simple React Counter component used inside an Astro page. The button updates the count when clicked. The client:load directive tells Astro to load the React component on the client side.

Astro
// File: Counter.jsx
import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)} aria-label="Increment count">
      Count: {count}
    </button>
  );
}

// File: src/pages/index.astro
---
import Counter from '../Counter.jsx';
---
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Astro React Example</title>
  </head>
  <body>
    <h1>Welcome to Astro with React</h1>
    <Counter client:load />
  </body>
</html>
OutputSuccess
Important Notes

Always add client: directives to React components in Astro to control when they load.

Use semantic HTML and ARIA labels inside React components for accessibility.

Astro renders static parts on the server and React handles dynamic parts on the client.

Summary

React components add interactivity inside Astro pages.

Use client:load or other client: directives to load React components properly.

This approach combines fast static content with dynamic React features.