#Using react component within astro component

3 messages · Page 1 of 1 (latest)

night canyon
#

Can I use React Component within Astro Component?

vocal valveBOT
#

Hi @night canyon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use React components inside Astro components.

  1. Install the React integration
npx astro add react
# or
pnpm astro add react
# or
yarn astro add react

This sets up @astrojs/react and configures it in astro.config.* via integrations: [react()]. [React integration]

  1. Import and use a React component in an .astro file
---
import MyReactComponent from '../components/MyReactComponent.jsx';
---

<html>
  <body>
    <h1>Use React components directly in Astro!</h1>
    <MyReactComponent />
  </body>
</html>

This pattern—importing a React component into an .astro file and using it like a normal component—is explicitly supported. [CRA migration]

  1. Important limitation

You cannot import .astro components inside React (or other framework) components; framework components must only import other framework components. If you need Astro content inside React, wrap the React component in an Astro component and pass Astro content via slots/children:

---
import MyReactComponent from '../components/MyReactComponent.jsx';
import MyAstroComponent from '../components/MyAstroComponent.astro';
---

<MyReactComponent>
  <MyAstroComponent slot="name" />
</MyReactComponent>

[Framework components]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: