# React に統合する

- Human documentation: [https://docs.univer.ai/ja-JP/guides/docs/getting-started/integrations/react](https://docs.univer.ai/ja-JP/guides/docs/getting-started/integrations/react)

- Agent Markdown: [https://docs.univer.ai/ja-JP/guides/docs/getting-started/integrations/react.md](https://docs.univer.ai/ja-JP/guides/docs/getting-started/integrations/react.md)

- Requested language: `ja-JP`

- Content language: `ja-JP`

- Documentation version: `1.1.0`

- Source: [docs/getting-started/integrations/react.ja-JP.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/docs/getting-started/integrations/react.ja-JP.mdx)

---

> [!NOTE]
> React コンポーネントをカスタムコンポーネントとして使う方法を探している場合は、[こちら](https://docs.univer.ai/ja-JP/guides/docs/ui/components.md#react) を参照してください。

React プロジェクトに Univer を統合する前に、[Univer のインストールと基本的な使い方](https://docs.univer.ai/ja-JP/guides/docs/getting-started/installation.md) を読み、React の基本概念とライフサイクルフックを理解しておいてください。

## React 18 & 19 で Web SDK を統合する

### 統合手順

1. `useEffect` 内で Univer を初期化
2. `useEffect` のクリーンアップで Univer を破棄

### サンプルコード

マウントごとに専用の子コンテナを使用します。外側の React のクリーンアップ後にマイクロタスクで破棄し、コミット中のネストした React root の同期アンマウントを避けます。

```tsx
import { UniverDocsCorePreset } from '@univerjs/preset-docs-core'
import UniverPresetDocsCoreJaJP from '@univerjs/preset-docs-core/locales/ja-JP'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import { useEffect, useRef } from 'react'

import '@univerjs/preset-docs-core/lib/index.css'

export function App() {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const host = containerRef.current
    if (!host) return
    const container = document.createElement('div')
    container.style.height = '100%'
    host.append(container)

    const { univer, univerAPI } = createUniver({
      locale: LocaleType.JA_JP,
      locales: {
        [LocaleType.JA_JP]: mergeLocales(
          UniverPresetDocsCoreJaJP,
        ),
      },
      presets: [
        UniverDocsCorePreset({
          container,
        }),
      ],
    })

    univerAPI.createDocument({})

    return () => {
      queueMicrotask(() => {
        univer.dispose()
        container.remove()
      })
    }
  }, [])

  return (
    <div ref={containerRef} style={{ height: 600 }} />
  )
}
```

## React 16.9+ & 17 で Web SDK を統合する

### 統合時の注意点

#### 互換性について

Univer のビュー層は React 18.3.1 をベースに開発されていますが、React 16.9+ & 17 でも最低限の互換性を提供しています。これは長期的な下位互換を保証するものではないため、可能であれば最新版への移行を推奨します。

#### ビルドツールの alias 設定

React 16.9+ & 17 では `react-dom/client` のエクスポートを模倣するため、ビルドツールの alias 設定が必要です。これを行わないと一部機能が正しく動作しません。

**Vite の設定例**

```typescript title="vite.config.ts"
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      'react-dom/client': path.resolve(__dirname, './src/client.ts'), // [!code ++]
    },
  },
})
```

```typescript title="src/client.ts"
import ReactDOM from 'react-dom'

export function createRoot(container: HTMLElement) {
  return {
    render: (element: JSX.Element) => {
      ReactDOM.render(element, container)
    },
  }
}
```

#### CDN/UMD 利用時の対応

`<script>` タグで React と Univer を読み込む場合、最新版の API に合わせるための補助コードが必要になることがあります。

```html
<script>
  /**
   * With the support for React 19[^1], UMD users may need additional adaptation.
   *
   * [^1]: [support for React 19] https://github.com/dream-num/univer/pull/4247
   */

  /**
   * Fix `Uncaught TypeError: client.createRoot is not a function`
   * If using UMD React < 18, you might need the following code.
   */
  ;(function (global) {
    'use strict'
    if (!global.ReactDOM) {
      throw new Error('ReactDOM must be loaded before ReactCreateRoot.')
    }
    const ReactDOM = global.ReactDOM
    if (!ReactDOM.createRoot) {
      ReactDOM.createRoot = function (container) {
        return {
          render: (element) => {
            ReactDOM.render(element, container)
          },
        }
      }
    }
  })(this)

  /**
   * Fix `Uncaught TypeError: jsxRuntime.jsx is not a function`
   * If using UMD React, you might need the following code.
   * Reference: https://unpkg.com/react@18.3.1/cjs/react-jsx-runtime.production.min.js
   */
  ;(function (global) {
    'use strict'
    if (!global.React) {
      throw new Error('React must be loaded before ReactJSXRuntime.')
    }
    const React = global.React
    if (!React.jsx || !React.jsxs) {
      const REACT_ELEMENT_TYPE = Symbol.for('react.element')
      const hasOwnProperty = Object.prototype.hasOwnProperty
      const RESERVED_PROPS = {
        key: true,
        ref: true,
        __self: true,
        __source: true,
      }
      const ReactCurrentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner
      function createReactElement(type, config, maybeKey) {
        const props = {}
        let key = null
        let ref = null
        if (maybeKey !== undefined) {
          key = `${maybeKey}`
        }
        if (config.key !== undefined) {
          key = `${config.key}`
        }
        if (config.ref !== undefined) {
          ref = config.ref
        }
        for (var propName in config) {
          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
            props[propName] = config[propName]
          }
        }
        if (type && type.defaultProps) {
          const defaultProps = type.defaultProps
          for (var propName in defaultProps) {
            if (props[propName] === undefined) {
              props[propName] = defaultProps[propName]
            }
          }
        }
        return {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          ref,
          props,
          _owner: ReactCurrentOwner.current,
        }
      }
      React.jsx = createReactElement
      React.jsxs = createReactElement
    }
  })(this)
</script>
```

### 統合手順

1. `useEffect` 内で Univer を初期化
2. `useEffect` のクリーンアップで Univer を破棄

### サンプルコード

```tsx
import { UniverDocsCorePreset } from '@univerjs/preset-docs-core'

import UniverPresetDocsCoreJaJP from '@univerjs/preset-docs-core/locales/ja-JP'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import { useEffect, useRef } from 'react'

import '@univerjs/preset-docs-core/lib/index.css'

export function App() {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const host = containerRef.current
    if (!host) return
    const container = document.createElement('div')
    container.style.height = '100%'
    host.append(container)

    const { univer, univerAPI } = createUniver({
      locale: LocaleType.JA_JP,
      locales: {
        [LocaleType.JA_JP]: mergeLocales(
          UniverPresetDocsCoreJaJP,
        ),
      },
      presets: [
        UniverDocsCorePreset({
          container,
        }),
      ],
    })

    univerAPI.createDocument({})

    return () => {
      queueMicrotask(() => {
        univer.dispose()
        container.remove()
      })
    }
  }, [])

  return (
    <div ref={containerRef} style={{ height: 600 }} />
  )
}
```
