> 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 %}
**パッケージをインストール**

追加する `@gitbook/embed` React プロジェクトに:

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

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

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

インポートする `GitBookProvider` 、 `GitBookFrame` components:

```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' } // 任意: 動的式のためのカスタムクレーム
          }}
        />
      </div>
    </GitBookProvider>
  );
}
```

{% hint style="info" %}
Assistant タブを使用する場合は、iframe に `allow="clipboard-write"` 埋め込みをレンダリングする iframe 上で。React の統合では iframe の設定はアプリ側で行います。スタンドアロン版 [Script タグ](/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: 'ようこそ!', subtitle: 'どのようにお手伝いできますか?' }}
    assistantName="Support Copilot"
    closeButton={true}
    suggestions={['GitBook とは何ですか?', 'どうやって始めればよいですか?']}
    actions={[
      {
        icon: 'circle-question',
        label: 'サポートに問い合わせる',
        onClick: () => window.open('https://support.example.com', '_blank')
      }
    ]}
    tools={[/* ... */]}
    visitor={{
      token: 'your-jwt-token',
      unsignedClaims: { userId: '123' }
    }}
  />
</GitBookProvider>
```

を省略すると、埋め込みは iframe の CSS に従います `colorScheme`。これにより、アプリのテーマに自動的に一致させられます。 `color-scheme`useGitBook フックで埋め込みを制御する
{% endstep %}

{% step %}
**フックを使って、埋め込みをプログラムから操作します:**

を使用するか、サーバーを `useGitBook` import { useGitBook } from "@gitbook/embed/react";

```jsx
function HelpButton() {

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

  条件に応じて埋め込みを表示する
}
```

{% endstep %}

{% step %}
**必要なときだけ埋め込みを表示します:**

const \[showEmbed, setShowEmbed] = useState(false);

```jsx
function App() {
  <button onClick={() => setShowEmbed(true)}>Get Help</button>

  return (
    <GitBookProvider siteURL="https://docs.company.com">
      {showEmbed && <GitBookFrame />}
      Next.js またはサーバーサイドレンダリングで使用する
    </GitBookProvider>
  );
}
```

{% endstep %}

{% step %}
**SSR の問題を避けるため、コンポーネントを動的にインポートします:**

import dynamic from "next/dynamic";

```jsx
const GitBookProvider = dynamic(

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

() => import("@gitbook/embed/react").then((mod) => mod.GitBookFrame),
  Props と設定
  const GitBookFrame = dynamic(
);
```

{% endstep %}
{% endstepper %}

## GitBookProvider の props:

**プロパティ**

| 必須         | 種類          | はい  | 既定  | 説明                                                     |
| ---------- | ----------- | --- | --- | ------------------------------------------------------ |
| `siteURL`  | `string`    | N/A | N/A | GitBook ドキュメントサイトの URL（例: `https://docs.company.com`). |
| `children` | `ReactNode` | N/A | N/A | プロバイダー内でレンダリングされる子コンポーネント。                             |

**GitBookFrame の props:**

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

| 必須              | 種類                            | はい  | 既定                      | 説明                            |
| --------------- | ----------------------------- | --- | ----------------------- | ----------------------------- |
| `className`     | `string`                      | いいえ | `null`                  | フレームコンテナに適用する CSS クラス名。       |
| `style`         | `object`                      | いいえ | `{}`                    | フレームコンテナに適用するインラインスタイル。       |
| `colorScheme`   | `これにより親ページまたはブラウザの設定を継承できます。` | いいえ | CSS から継承 `color-scheme` | に渡されます。                       |
| `assistantName` | `string`                      | いいえ | `null`                  | UI に表示される Assistant 名を上書きします。 |
| `closeButton`   | `真偽値`                         | いいえ | `null`                  | Assistant 内に閉じるボタンを表示します。     |
| `visitor`       | `object`                      | いいえ | `{}`                    | 認証済みアクセスのオプション（以下を参照）。        |

**useGitBook フック:**

次を返します `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`

## 設定オプション

設定オプションは、次の props として利用できます: `<GitBookFrame>`:

### `タブ`

で利用できます。

検索はデフォルトで有効です。もし `タブ`、埋め込みには指定したタブのみが表示されます。

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

### `colorScheme`

に渡されます。

埋め込みの配色を上書きします。 `color-scheme`指定しない場合、埋め込みは iframe の CSS に従い、

* **種類**: `これにより親ページまたはブラウザの設定を継承できます。`

### `actions`

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

**注**: これは以前は `buttons`と呼ばれていました。 `actions` 代わりにこちらを使用してください。

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

### `greeting`

Assistant タブに表示されるウェルカムメッセージ。

* **種類**: `{ title: string, subtitle: string }`

### `assistantName`

UI に表示される Assistant 名を上書きします。

* **種類**: `string`
* **最大長**: `32` 文字

### `closeButton`

Assistant 内に閉じるボタンを表示します。

* **種類**: `真偽値`

### `suggestions`

Assistant のウェルカム画面に表示される推奨質問。

* **種類**: `string[]`

### `trademark`

Docs Embed フッターや Assistant のブランド表記を含む、埋め込み UI 内の GitBook 商標を表示または非表示にします。

* **種類**: `真偽値`
* **既定**: `true`

### `tools`

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

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

### `visitor` (認証済みアクセス)

次に使用されます [Adaptive Content](/docs/documentation/ja-gitbook-documentation/publish/adaptive-content.md) 、 [認証済みアクセス](/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 が公開済みドキュメントと一致しない
* **– 」「を確認してください** prop が実際のドキュメントサイトの URL と完全に一致していることを `siteURL` provider の外で 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
