跳到內容

@astrojs/ react

本頁內容尚未翻譯。

This Astro integration enables rendering and client-side hydration for your React components.

Astro includes an astro add command to automate the setup of official integrations. If you prefer, you can install integrations manually instead.

To install @astrojs/react, run the following from your project directory and follow the prompts:

Terminal window
npx astro add react

If you run into any issues, feel free to report them to us on GitHub and try the manual installation steps below.

First, install the @astrojs/react package:

Terminal window
npm install @astrojs/react

Most package managers will install associated peer dependencies as well. If you see a Cannot find package 'react' (or similar) warning when you start up Astro, you’ll need to install react and react-dom with its type definitions:

Terminal window
npm install react react-dom @types/react @types/react-dom

Then, apply the integration to your astro.config.* file using the integrations property:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [react()],
});

And add the following code to the tsconfig.json file.

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

To use your first React component in Astro, head to our UI framework documentation. You’ll explore:

  • 📦 how framework components are loaded,
  • 💧 client-side hydration options, and
  • 🤝 opportunities to mix and nest frameworks together

The @astrojs/react integration provides two functions for use with Astro Actions: withState() and getActionState().

These are used with React’s useActionState() hook to read and update client-side state when triggering actions during form submission.

Type: (action: FormFn<T>) => (state: T, formData: FormData) => FormFn<T>

新增於: @astrojs/react@4.4.0

You can pass withState() and the action you want to trigger to React’s useActionState() hook as the form action function. The example below passes a like action to increase a counter along with an initial state of 0 likes.

Like.tsx
import { actions } from 'astro:actions';
import { withState } from '@astrojs/react/actions';
import { useActionState } from "react";
export function Like({ postId }: { postId: string }) {
const [state, action, pending] = useActionState(
withState(actions.like),
{ data: 0, error: undefined }, // initial likes and errors
);
return (
<form action={action}>
<input type="hidden" name="postId" value={postId} />
<button disabled={pending}>{state.data} ❤️</button>
</form>
);
}

The withState() function will match the action’s types with React’s expectations and preserve metadata used for progressive enhancement, allowing it to work even when JavaScript is disabled on the user’s device.

Type: (context: ActionAPIContext) => Promise<T>

新增於: @astrojs/react@4.4.0

You can access the state stored by useActionState() on the server in your action handler with getActionState(). It accepts the Astro API context, and optionally, you can apply a type to the result.

The example below gets the current value of likes from a counter, typed as a number, in order to create an incrementing like action:

actions.ts
import { defineAction, type SafeResult } from 'astro:actions';
import { z } from 'astro/zod';
import { getActionState } from '@astrojs/react/actions';
export const server = {
like: defineAction({
input: z.object({
postId: z.string(),
}),
handler: async ({ postId }, ctx) => {
const { data: currentLikes = 0, error } = await getActionState<SafeResult<any, number>>(ctx);
// handle errors
if (error) throw error;
// write to database
return currentLikes + 1;
},
})
};

When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed.

Use the include (required) and exclude (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to include for each framework you are using. Wildcards may be used to include multiple file paths.

We recommend placing common framework components in the same folder (e.g. /components/react/ and /components/solid/) to make specifying your includes easier, but this is not required:

astro.config.mjs
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
import react from '@astrojs/react';
import svelte from '@astrojs/svelte';
import vue from '@astrojs/vue';
import solid from '@astrojs/solid-js';
export default defineConfig({
// Enable many frameworks to support all different kinds of components.
// No `include` is needed if you are only using a single JSX framework!
integrations: [
preact({
include: ['**/preact/*'],
}),
react({
include: ['**/react/*'],
}),
solid({
include: ['**/solid/*'],
}),
],
});

Type: boolean | object
Default: false

新增於: @astrojs/react@7.0.0

By default, @astrojs/react uses Oxc to compile your JSX and enable Fast Refresh. It doesn’t memoize your components or hooks.

Set compiler: true to automatically memoize client components and hooks with the experimental Oxc React Compiler. This can reduce unnecessary re-renders without writing useMemo(), useCallback(), or React.memo() yourself.

The compiler requires the installation of oxc-transform-react:

Terminal window
npm install -D oxc-transform-react

The compiler targets your installed React version. React 17 and 18 don’t ship the compiler runtime helpers. If your project uses one of these versions, also install react-compiler-runtime:

Terminal window
npm install react-compiler-runtime

Then, enable the compiler in your React integration:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
integrations: [
react({ compiler: true }),
],
});

You can also pass an object for finer control over the compiler configuration.

The following example configures compilationMode to compile only components and hooks marked with a "use memo" directive:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
integrations: [
react({
compiler: {
compilationMode: 'annotation',
},
}),
],
});

The compiler applies wherever the integration’s include and exclude options apply. It skips server rendering, dependencies, and .astro files.

Children passed into a React component from an Astro component are parsed as plain strings, not React nodes.

For example, the <ReactComponent /> below will only receive a single child element:

---
import ReactComponent from './ReactComponent';
---
<ReactComponent>
<div>one</div>
<div>two</div>
</ReactComponent>

If you are using a library that expects more than one child element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker.

You can set the experimental flag experimentalReactChildren to tell Astro to always pass children to React as React virtual DOM nodes. There is some runtime cost to this, but it can help with compatibility.

You can enable this option in the configuration for the React integration:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [
react({
experimentalReactChildren: true,
}),
],
});

Astro streams the output of React components by default. However, you can disable this behavior by enabling the experimentalDisableStreaming option. This is particularly helpful for supporting libraries that don’t work well with streaming, like some CSS-in-JS solutions.

To disable streaming for all React components in your project, configure @astrojs/react with experimentalDisableStreaming: true:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [
react({
experimentalDisableStreaming: true,
})
]
});

@astrojs/react v7.0.0 replaces Babel with Oxc to compile JSX and enable Fast Refresh, and upgrades to @vitejs/plugin-react v6.

Configure custom Babel transforms with @rolldown/plugin-babel in vite.plugins instead of the removed babel option.

Install @rolldown/plugin-babel and @babel/core:

Terminal window
npm install -D @rolldown/plugin-babel @babel/core

Then, move your Babel plugins and presets to a babel() plugin under vite.plugins.

The following example moves babel-plugin-styled-components out of the removed babel option:

astro.config.mjs
import react from '@astrojs/react';
import babel from '@rolldown/plugin-babel';
import { defineConfig } from 'astro/config';
export default defineConfig({
integrations: [
react({
babel: {
plugins: ['babel-plugin-styled-components'],
},
}),
react(),
],
vite: {
plugins: [
babel({
plugins: ['babel-plugin-styled-components'],
}),
],
},
});

For conditional transforms previously configured with a babel callback, see the overrides and preset hooks of @rolldown/plugin-babel.

You can combine babel() with compiler: true. If your Babel configuration includes babel-plugin-react-compiler, remove it first. This avoids applying React Compiler transformations twice to the same components.

更多

UI 框架

配接器

其他

貢獻 社群 贊助