@astrojs/ react
このAstroインテグレーションは、Reactコンポーネントのレンダリングとクライアントサイドハイドレーションを有効にします。
インストール
Section titled “インストール”Astroには、公式インテグレーションのセットアップを自動化するためのastro addコマンドが含まれています。もしよろしければ、手動でインテグレーションをインストールできます。
@astrojs/reactをインストールするには、プロジェクトディレクトリから次のコマンドを実行し、プロンプトに従ってください。
npx astro add reactpnpm astro add reactyarn astro add react問題が発生した場合は、GitHubで報告してください。そして、以下の手動インストール手順を試してください。
手動インストール
Section titled “手動インストール”まず、@astrojs/reactパッケージをインストールします。
npm install @astrojs/reactpnpm add @astrojs/reactyarn add @astrojs/reactほとんどのパッケージマネージャーは、関連するピア依存関係もインストールします。Astroの起動時にCannot find package 'react'(または同様の)警告が表示される場合は、reactとreact-domおよびその型定義をインストールする必要があります。
npm install react react-dom @types/react @types/react-dompnpm add react react-dom @types/react @types/react-domyarn add react react-dom @types/react @types/react-dom次に、integrationsプロパティを使用して、インテグレーションをastro.config.*ファイルに適用します。
import { defineConfig } from 'astro/config';import react from '@astrojs/react';
export default defineConfig({ // ... integrations: [react()],});そして、tsconfig.jsonファイルに次のコードを追加します。
{ "extends": "astro/tsconfigs/strict", "include": [".astro/types.d.ts", "**/*"], "exclude": ["dist"], "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "react" }}Astroで最初のReactコンポーネントを使用するには、UIフレームワークのドキュメントにアクセスしてください。以下について探求します。
- 📦 フレームワークコンポーネントがどのように読み込まれるか
- 💧 クライアントサイドハイドレーションのオプション
- 🤝 フレームワークを混在させてネストする機会
useActionState()によるアクションの統合
Section titled “useActionState()によるアクションの統合”@astrojs/reactインテグレーションは、Astroアクションで使用するためのwithState()とgetActionState()の2つの関数を提供します。
これらは、フォーム送信時にアクションをトリガーする際のクライアントサイドの状態の読み取りと更新のために、ReactのuseActionState()フックとともに使用します。
withState()
Section titled “withState()”Type: (action: FormFn<T>) => (state: T, formData: FormData) => FormFn<T>
@astrojs/react@4.4.0
New
ReactのuseActionState()フックに、withState()とトリガーしたいアクションをフォームアクション関数として渡せます。以下の例では、likeアクションを渡して初期状態0のカウンターを増加させています。
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 }, // いいねとエラーの初期値 );
return ( <form action={action}> <input type="hidden" name="postId" value={postId} /> <button disabled={pending}>{state.data} ❤️</button> </form> );}withState()関数は、アクションの型をReactの期待する型と一致させ、プログレッシブエンハンスメントに使用されるメタデータを保持するため、ユーザーのデバイスでJavaScriptが無効な場合でも動作します。
getActionState()
Section titled “getActionState()”Type: (context: ActionAPIContext) => Promise<T>
@astrojs/react@4.4.0
New
useActionState()に保存された状態に、サーバーでgetActionState()を使用してアクションのhandler内からアクセスできます。Astro APIコンテキスト (EN)を受け取り、オプションで結果に型を適用できます。
以下の例では、likeアクションを作成するために、カウンターから現在のいいね数を数値型として取得しインクリメントしています。
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);
// エラーを処理する if (error) throw error;
// データベースに書き込む return currentLikes + 1; }, })};複数のJSXフレームワークの組み合わせ
Section titled “複数のJSXフレームワークの組み合わせ”同じプロジェクトで複数のJSXフレームワーク(React、Preact、Solid)を使用している場合、Astroは各コンポーネントに対してどのJSXフレームワーク固有の変換を使用すべきかを判断する必要があります。プロジェクトにJSXフレームワークインテグレーションを1つだけ追加した場合、追加の設定は不要です。
include(必須)およびexclude(任意)設定オプションを使用して、どのファイルがどのフレームワークに属するかを指定します。使用しているフレームワークごとに、includeにファイルやフォルダの配列を指定します。ワイルドカードを使用して複数のファイルパスを含められます。
共通のフレームワークコンポーネントを同じフォルダに配置すること(例:/components/react/や/components/solid/)をお勧めしますが、必須ではありません。
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({ // 多くのフレームワークを有効にして、さまざまな種類のコンポーネントをサポートします。 // JSXフレームワークを1つだけ使用している場合、`include`は不要です! integrations: [ preact({ include: ['**/preact/*'], }), react({ include: ['**/react/*'], }), solid({ include: ['**/solid/*'], }), ],});子要素のパース
Section titled “子要素のパース”AstroコンポーネントからReactコンポーネントに渡された子要素は、Reactノードではなくプレーンな文字列としてパースされます。
たとえば、以下の<ReactComponent />は単一の子要素のみを受け取ります。
---import ReactComponent from './ReactComponent';---
<ReactComponent> <div>one</div> <div>two</div></ReactComponent>複数の子要素が渡されることを期待するライブラリを使用している場合(たとえば、特定の要素を異なる場所にスロットするため)、これがブロッカーになる可能性があります。
実験的フラグexperimentalReactChildrenを設定すると、Astroは常にReactの仮想DOMノードとしてReactに子要素を渡すようになります。これにはランタイムコストがかかりますが、互換性の向上に役立ちます。
このオプションは、Reactインテグレーションの設定で有効にできます。
import { defineConfig } from 'astro/config';import react from '@astrojs/react';
export default defineConfig({ // ... integrations: [ react({ experimentalReactChildren: true, }), ],});ストリーミングの無効化(実験的)
Section titled “ストリーミングの無効化(実験的)”AstroはデフォルトでReactコンポーネントの出力をストリーミングします。ただし、experimentalDisableStreamingオプションを有効にすることでこの動作を無効にできます。これは、一部のCSS-in-JSソリューションなど、ストリーミングと相性が悪いライブラリをサポートする場合に特に役立ちます。
プロジェクト内のすべてのReactコンポーネントのストリーミングを無効にするには、@astrojs/reactにexperimentalDisableStreaming: trueを設定します。
import { defineConfig } from 'astro/config';import react from '@astrojs/react';
export default defineConfig({ // ... integrations: [ react({ experimentalDisableStreaming: true, }) ]});