Astro JS - React.js Integration



What is React.js?

ReactJS is a free and open-source front-end JavaScript library which is used to develop various interactive user-interfaces. It is a simple, feature rich and component based UI library. React is famous for it's component based architecture and virtual DOM. This allows developers to build reusable UI components and optimize the performance of web applications. Also react library provides large set of ready-made components and hooks to build complex UIs. Astro allows us to integrate react components in astro applications.

React Integration in Astro

Astro provides built-in support for React.js by using React adapter to render React components. You can write your favorite UI components in React and optimize them for performance using Astro. Let's see how to integrate React.js with Astro.

Get Started With React in Astro

Follow the steps below to integrate React.js with Astro:

Step 1: Install React Adapter

First, you need to install the React adapter for Astro. You can do this using the following command:

>> npm install @astrojs/react

Step 2: Configure React in Astro

Next step is to apply the integration to your astro.config.ts and tsconfig.json files using the integrations property:

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

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

Now, Add following code to your typescript configuration file (tsconfig.json)

{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"],
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react"
  }
}

Step 3: Create a React Component

Now, you can create a React component in your Astro project. You can keep your components in the '/src/components' directory. Here is an example of a simple React component:

// 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 4: Use the React Component in Astro Page

Now, you can use the React component in your 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.

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

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

<Layout>
    <h1>Welcome to Astro</h1>
    <p>This content is static.</p>
    
    <!-- React Counter Component -->
    <Counter />
</Layout>

Step 5: Run the Astro Project

Now, if you run Astro project, you can see the React component in your Astro page. The counter component will increase the count by 1 when the button is clicked.

Astro React Integration
Advertisements