Use React component in Astro

By

Published · Updated

Tagged: Astro, React

Use a React component in Astro: install the integration, render it as static HTML by default, pick the right client directive for interactivity, pass props and children, and avoid the common pitfalls.

Install Astro’s React integration:

npx astro add react

This installs @astrojs/react and React, and adds the integration to your astro.config.mjs file:

import { defineConfig } from 'astro/config'
import react from '@astrojs/react'

export default defineConfig({
  integrations: [react()],
})

If you prefer to do it by hand, run npm install @astrojs/react react react-dom and add the same lines yourself.

Render a React component

Create src/components/Greeting.jsx:

export default function Greeting({ name }) {
  return <p>Hello {name}</p>
}

Import and render it in a .astro component:

---
import Greeting from '../components/Greeting.jsx'
---

<Greeting name="Flavio" />

Astro renders this component to HTML during the build or server render. No React JavaScript is sent to the browser.

This is the part that surprises people coming from React. Take this counter:

import { useState } from 'react'

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  )
}

If you render it with <Counter start={5} />, you get a button that says “Clicked 5 times”, and clicking it does nothing. There’s no error. The HTML is there, but the JavaScript that runs onClick and useState never reaches the browser.

Make it interactive with a client directive

If the component uses state, event handlers, effects, or another browser API, hydrate it with a client directive:

<Counter client:load start={5} />

Now Astro renders the HTML on the server as before, and then loads React in the browser to make the component interactive. Astro calls a component like this an island.

client:load is one of several directives. Pick the one that matches how soon the user needs the component:

DirectiveWhen it hydratesGood for
client:loadAs soon as the page loadsUI that must work right away, like a buy button
client:idleWhen the browser is idle after the page loadsLess urgent UI
client:visibleWhen the component scrolls into viewThings far down the page
client:media="(max-width: 50em)"When the CSS media query matchesA mobile menu toggle
client:only="react"Only in the browser, skips server renderingComponents that need window or document

client:idle and client:visible take options. client:idle={{ timeout: 500 }} hydrates after at most 500ms, even if the browser is still busy. client:visible={{ rootMargin: '200px' }} starts hydrating when the component is 200px away from the viewport.

Components that use window or document

If your component reads window or document while rendering, the build fails:

ReferenceError: window is not defined

That’s because Astro runs the component on the server first, even with client:load, and there’s no window on the server.

You have two options.

Read browser APIs inside useEffect, which only runs in the browser. This is the better option when it’s easy to do, because you still get server-rendered HTML.

Or skip the server render with client:only. You must say which framework the component uses, because Astro doesn’t run it at build time to find out. You can pass some fallback content to show until it loads:

<WindowSize client:only="react">
  <p slot="fallback">Loading…</p>
</WindowSize>

Passing props

Props work like in React. With static components you can pass anything.

With hydrated components (any client:* directive), Astro has to send the props to the browser, so they must be serializable. Strings, numbers, arrays, plain objects, Date, Map, Set and URL are fine.

Functions are not. This looks like it works:

<Picker client:load onPick={() => console.log('picked')} />

The server render gets the function, but Astro can’t send a function to the browser. I checked the built HTML, and the prop was serialized as null. So the component hydrates without your callback.

If an island needs a callback, define it inside the React component, or move the parent logic into a React component too.

Passing children and slots

Children go into the children prop, as in React:

<Card title="Hi">
  <p>Some text</p>
</Card>
export default function Card({ title, children }) {
  return (
    <div>
      <h2>{title}</h2>
      {children}
    </div>
  )
}

Named slots become props. A kebab-case slot name turns into camelCase, so slot="social-links" arrives as the socialLinks prop:

<Card title="Hi">
  <p>Some text</p>
  <a slot="social-links" href="https://x.com/flaviocopes">X</a>
</Card>

One limit: content you pass from Astro to React reaches React as plain HTML, not as React elements. You can render it, but you can’t loop over it with React.Children or read its props. If a library needs that, the React integration has an experimentalReactChildren option that passes children as React nodes, at some runtime cost.

Things you can’t do

For more on how Astro components themselves work, see my Astro components post.

Want me to talk about your product? You can sponsor this site.

Related posts about astro: