> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/implementation/react.md).

# React

事前構築済みの React コンポーネントを使って、React アプリケーションに Docs Embed を追加します

Reactプロジェクト向けに、GitBookはドキュメントを簡単かつ慣用的な方法で埋め込める、構築済みのコンポーネントを提供しています。状態管理、コンテキスト、ライフサイクルはコンポーネントが自動で処理します。

## 手順

{% stepper %}
{% step %}
**パッケージをインストールする**

Reactプロジェクトに `@gitbook/embed` を追加します。

```bash
npm install @gitbook/embed
```

API リファレンスとソースコードの詳細については、GitHub の [`@gitbook/embed` パッケージを参照してください](https://github.com/GitbookIO/gitbook/tree/main/packages/embed).
{% endstep %}

{% step %}
**Reactコンポーネントをインポートする**

次のコンポーネントをインポートします。 `GitBookProvider` と `GitBookFrame` ：

```jsx
import {
  GitBookProvider,
  GitBookFrame,
} from "@gitbook/embed/react";
```

{% endstep %}

{% step %}
**アプリをGitBookProviderでラップする**

コンポーネントツリーのルート、または埋め込みが必要な箇所にプロバイダーを追加します。

```jsx
function App() {
  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <YourAppContent />
    </GitBookProvider>
  );
}
```

{% endstep %}

{% step %}
**GitBookFrameコンポーネントを追加する**

埋め込みを表示する場所にフレームコンポーネントを配置します。

```jsx
function App() {
  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <div className="app">
        <YourAppContent />
        <GitBookFrame
          visitor={{
            token: 'your-jwt-token', // 任意: Adaptive Content または認証済みアクセス用
            unsignedClaims: { userId: '123' } // Optional: custom claims for dynamic expressions
          }}
        />
      </div>
    </GitBookProvider>
  );
}
```

{% hint style="info" %}
Assistantタブを使用する場合は、埋め込みを表示するiframeに `allow="clipboard-write"` を設定します。Reactインテグレーションでは、iframeの設定はアプリ側で行います。スタンドアロンの [Scriptタグ](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/implementation/script.md) による実装では、この設定が自動的に追加されます。
{% endhint %}
{% endstep %}

{% step %}
**埋め込みをカスタマイズする**

フレームコンポーネントに設定用のpropsを渡します。

```jsx
<GitBookProvider siteURL="https://docs.company.com">
  <GitBookFrame
    trademark={false}
    tabs={['assistant', 'search', 'docs']}
    colorScheme="dark"
    greeting={{ title: 'Welcome!', subtitle: 'How can I help?' }}
    assistantName="Support Copilot"
    closeButton={true}
    suggestions={['What is GitBook?', 'How do I get started?']}
    actions={[
      {
        icon: 'circle-question',
        label: 'Contact Support',
        onClick: () => window.open('https://support.example.com', '_blank')
      }
    ]}
    tools={[/* ... */]}
    visitor={{
      token: 'your-jwt-token',
      unsignedClaims: { userId: '123' }
    }}
  />
</GitBookProvider>
```

を省略すると、 `colorScheme`、埋め込みはiframeのCSS `color-scheme`に従います。これにより、アプリのテーマに自動的に合わせられます。
{% endstep %}

{% step %}
**useGitBookフックで埋め込みを制御する**

以下の `useGitBook` フックを使用すると、埋め込みをプログラムから操作できます。

```jsx
import { useGitBook } from "@gitbook/embed/react";

function HelpButton() {
  const gitbook = useGitBook();
  const frameURL = gitbook.getFrameURL({ visitor: { token: '...' } });
  
  const handleNavigate = () => {
    const iframe = document.createElement('iframe');
    iframe.src = frameURL;
    iframe.allow = 'clipboard-write';
    const frame = gitbook.createFrame(iframe);
    frame.navigateToPage('/getting-started');
    frame.navigateToAssistant();
    frame.postUserMessage('How do I get started?');
  };

  return <button onClick={handleNavigate}>Get Help</button>;
}
```

{% endstep %}

{% step %}
**条件に応じて埋め込みをレンダリングする**

必要な場合にのみ埋め込みを表示します。

```jsx
function App() {
  const [showEmbed, setShowEmbed] = useState(false);

  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <button onClick={() => setShowEmbed(true)}>Get Help</button>
      {showEmbed && <GitBookFrame />}
    </GitBookProvider>
  );
}
```

{% endstep %}

{% step %}
**Next.js またはサーバーサイドレンダリングで使用する**

SSR に関する問題を避けるため、コンポーネントを動的にインポートします。

```jsx
import dynamic from "next/dynamic";

const GitBookProvider = dynamic(
  () => import("@gitbook/embed/react").then((mod) => mod.GitBookProvider),
  { ssr: false }
);

const GitBookFrame = dynamic(
  () => import("@gitbook/embed/react").then((mod) => mod.GitBookFrame),
  { ssr: false }
);
```

{% endstep %}
{% endstepper %}

## Props と設定

**GitBookProvider の Props:**

| Prop       | 種類          | 必須 | デフォルト | 説明                                                     |
| ---------- | ----------- | -- | ----- | ------------------------------------------------------ |
| `siteURL`  | `string`    | はい | 該当なし  | GitBook ドキュメントサイトの URL（例: `https://docs.company.com`). |
| `children` | `ReactNode` | はい | 該当なし  | プロバイダー内にレンダリングする子コンポーネント。                              |

**GitBookFrame の Props:**

すべての設定オプションは、 `<GitBookFrame>`に Props として渡せます。利用可能なオプションについては、以下の「設定」セクションを参照してください。

| Prop            | 種類                  | 必須  | デフォルト                   | 説明                       |
| --------------- | ------------------- | --- | ----------------------- | ------------------------ |
| `className`     | `string`            | いいえ | `null`                  | フレームコンテナーに適用する CSS クラス名。 |
| `style`         | `object`            | いいえ | `{}`                    | フレームコンテナーに適用するインラインスタイル。 |
| `colorScheme`   | `'light' \| 'dark'` | いいえ | CSS から継承 `color-scheme` | 埋め込みの配色を上書きします。          |
| `assistantName` | `string`            | いいえ | `null`                  | UI に表示されるアシスタント名を上書きします。 |
| `closeButton`   | `boolean`           | いいえ | `null`                  | アシスタント内に閉じるボタンを表示します。    |
| `visitor`       | `object`            | いいえ | `{}`                    | 認証済みアクセスのオプション（以下を参照）。   |

**useGitBook Hook:**

次のメソッドを持つ `GitBookClient` インスタンスを返します。

* `getFrameURL(options?: { visitor?: {...}, colorScheme?: 'light' | 'dark' })` → `string` - iframeのURLを取得
* `createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - フレームクライアントを作成

フレームクライアントは次の機能を提供します。

* `navigateToPage(path: string)` → `void`
* `navigateToAssistant()` → `void`
* `postUserMessage(message: string)` → `void`
* `clearChat()` → `void`
* `configure(settings: {...})` → `void`
* `on(event: string, listener: Function)` → `() => void`

## 設定オプション

設定オプションは `<GitBookFrame>`:

### `tabs`

表示するタブを上書きします。

検索はデフォルトで有効になっています。 `tabs`を設定すると、埋め込みには指定したタブのみが表示されます。

* **型**: `('assistant' | 'search' | 'docs')[]`

### `colorScheme`

埋め込みの配色を上書きします。

省略すると、埋め込みコンテンツは iframe の CSS `color-scheme`に従い、親ページまたはブラウザーの設定を継承します。

* **型**: `'light' | 'dark'`

### `actions`

タブと並んでサイドバーに表示されるカスタムアクションボタンです。各アクションボタンは、クリックされるとコールバックをトリガーします。

**注**：以前は `buttons`が使われていました。代わりに `actions` を使用してください。

* **型**: `Array<{ icon: string, label: string, onClick: () => void }>`

### `greeting`

アシスタントタブに表示されるウェルカムメッセージ。

* **型**: `{ title: string, subtitle: string }`

### `assistantName`

UI に表示されるアシスタント名を上書きします。

* **型**: `string`
* **最大文字数**: `32` 文字

### `closeButton`

アシスタント内に閉じるボタンを表示します。

* **型**: `boolean`

### `suggestions`

アシスタントのウェルカム画面に表示される提案質問。

* **型**: `string[]`

### `trademark`

Docs Embed フッターやアシスタントのブランディングを含む、埋め込み UI 内の GitBook 商標の表示/非表示を切り替えます。

* **型**: `boolean`
* **デフォルト**: `true`

### `tools`

Assistant を拡張するカスタム AI ツールです。詳しくは [カスタムツールの作成](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/configuration/creating-custom-tools.md) をご覧ください。

* **型**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

### `visitor` （認証済みアクセス）

次の用途に使用します。 [アダプティブコンテンツ](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/adaptive-content.md) および [認証済みアクセス](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access.md).

* **型**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`

## よくある落とし穴

* **GitBookProviderでラップされていない** –  `GitBookFrame` が機能するには、親要素に `GitBookProvider` が必要です。
* **動的インポートを使わずにSSRで使用する** – このコンポーネントはブラウザーAPIを使用するため、Next.jsやその他のSSRフレームワークでは動的にインポートする必要があります。
* **siteURLが公開ドキュメントと一致しない** – `siteURL` プロパティが、公開中のドキュメントサイトの URL と完全に一致していることを確認してください。
* **プロバイダーの外部で useGitBook を呼び出している** – `useGitBook` フックは、 `GitBookProvider`.
* **ツリー内に複数のプロバイダーがある** – 複数の `GitBookProvider` インスタンスをネストしないでください。コンテキストの競合が発生する可能性があります。
* **古いコンポーネント名を使用している** – コンポーネント名は現在、 `GitBookFrame`であり、 `GitBookAssistantFrame`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/implementation/react.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
