メインコンテンツにスキップ
チュートリアル

Building Mobile Apps with React and Capacitor

Learn how to build a mobile app using React, Capacitor, and add Capgo Native Navigation, Transitions, and iOS layout best practices.

記事のクレジット

マーティン・ドナディュー

ライター

バレリア

レビュアー

ジョーダン

編集者

Building Mobile Apps with React and Capacitor

このチュートリアルでは、Capacitorを使用してReactアプリをモバイルアプリに変換する方法を説明します。 React app and transition to native mobile development using Capacitor. You can also add Capgo Native Navigation and Transitions for a native mobile feel, and use tailwind-capacitor for safe areas.

Capacitorを使用すると、Reactアプリをモバイルアプリに変換できます。

このチュートリアルでは、Reactアプリをモバイルアプリに変換する方法を説明します。

This tutorial will guide you through the process, starting with a new React app and then incorporating Capacitor to move into the realm of native mobile apps. You can also use Capgo Native Navigation, Transitions, and tailwind-capacitor for safe areas.

About Capacitor

Capacitorを使用すると、モバイルアプリを簡単に作成できます。

With Capacitor, you get a fantastic native mobile app without any complicated setup or steep learning curve. Its slim API and streamlined functionality make it a breeze to integrate into your project. Trust me, you’ll be amazed at how effortless it is to achieve a fully functional native app with Capacitor!

Capacitorを使用すると、モバイルアプリを簡単に作成できます。

このチュートリアルでは、最もシンプルな方法でReactアプリケーションを開始する方法を紹介します。

npx create-react-app my-app

nativeモバイルアプリを作成するには、プロジェクトのエクスポートが必要です。 export package.jsonに、プロジェクトをビルドしてエクスポートするためのシンプルなスクリプトを追加します。 問題なく実行できます。プロジェクトのルートディレクトリに新しいフォルダが表示されます。 このフォルダは後で__CAPGO_KEEP_0__によって使用されますが、現在は正しく設定する必要があります。

{
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

__CAPGO_KEEP_0__をReactアプリに追加する npm run build Webアプリをnativeモバイルコンテナにパッケージ化するには、初期ステップを実行する必要がありますが、その後は単一のコマンドを実行するだけです。

This folder will be used by Capacitor later on, but for now, we must set it up correctly.

Adding Capacitor to Your React App

pagePath sync /ja/blog/create-react-mobile-apps-with-capacitor/

Firstly, we can install the Capacitor CLI Capacitorを開発依存としてインストールし、プロジェクト内でセットアップすることができます。セットアップ中に、名前とバンドルIDのデフォルト値を承認するには「Enter」を押すことができます。

次に、iOSとAndroidプラットフォームのためのコアパッケージと関連パッケージをインストールする必要があります。

Finally, we can add the platforms, and Capacitor will create folders for each platform at the root of our project:

# Install the Capacitor CLI locally
npm install -D @capacitor/cli

# Initialize Capacitor in your React project
npx cap init

# Install the required packages
npm install @capacitor/core @capacitor/ios @capacitor/android

# Add the native platforms
npx cap add ios
npx cap add android

この時点で、Reactプロジェクト内に新しい ioscontext":"Page/area: Capgo marketing website. Role: Short UI label or navigation item. Seen in: page trust.astro. Message key `and` (And)." android

フォルダが観察できます。

これらは実際のネイティブプロジェクトです! Android Studio. For iOS, you need a Mac and should install Xcode.

Additionally, you should find a capacitor.config.ts file in your project, which contains some fundamental Capacitor settings utilized during the sync. The only thing you need to pay attention to is the webDirwhich must point to the result of your build command. Currently, it is inaccurate.

To rectify this, open the capacitor.config.json file and update the webDir:

{
  "appId": "com.example.app",
  "appName": "my-app",
  "webDir": "out",
  "bundledWebRuntime": false
}

実際に動作させるには、以下のコマンドを実行してみてください。

npm run build
npx cap sync

最初のコマンド npm run build は、React プロジェクトを単にビルドし、静的ビルドをエクスポートします。

2 番目のコマンド npx cap sync will sync all the web code into the right places of the native platforms so they can be displayed in an app.

Sync コマンドは、ネイティブ プラットフォームを更新し、プラグインをインストールする可能性があるため、新しい Capacitor プラグインをインストールした場合 npx cap sync 再度実行する必要があります。

気づかないうちに、実際に完了しています。 では、デバイスでアプリを確認してみましょう。

ネイティブ アプリをビルドしてデプロイする

iOS アプリを開発するには、 Xcode がインストールされている場合、Androidアプリの場合には Android Studio がインストールされている必要があります。また、App Storeでアプリを配布する場合、iOSの場合にはApple Developer Programに登録し、Androidの場合にはGoogle Play Consoleに登録する必要があります。

nativeモバイル開発に慣れていない場合は、Capacitor CLI を使用して、両方のネイティブプロジェクトを簡単に開くことができます。

npx cap open ios
npx cap open android

ネイティブプロジェクトを設定した後、実機にアプリをデプロイするのは簡単です。Android Studioでは、設定を変更することなく実機にアプリをデプロイすることができます。以下の例を参照してください。

android-studio-run

Xcodeでは、実機にアプリをデプロイするには署名アカウントを設定する必要があります。シミュレーターにのみアプリをデプロイする場合は、署名アカウントを設定する必要はありません。署名アカウントを設定する場合は、Xcodeがガイドを提供します (ただし、開発者プログラムに登録する必要があります)。署名アカウントを設定した後、実機にアプリをデプロイするには、上部で実機を選択し、実行をクリックするだけです。以下の例を参照してください。

xcode-run

成功しました! React Webアプリをモバイルデバイスにデプロイしました。以下の例を参照してください。

react-mobile-app

しかし、開発中にはもっと速い方法があります…

Capacitor Live Reload

現在、すべてのモダンフレームワークでホットリロードができるようになっているので、同じ機能をモバイルデバイスで利用できるようになります。 モバイルデバイスで 最小限の手間で!

ローカルホストのアプリケーションにアクセスし、ライブリロードを有効にするには、__CAPGO_KEEP_0__ アプリが特定のURLからコンテンツを読み込むように設定する必要があります。 ローカルIPアドレスを調べる必要があります。Macを使用している場合は、ターミナルで以下のコマンドを実行して調べることができます。 by having the Capacitor app load the content from the specific URL.

次に、IPv4アドレスを探してください。

ipconfig getifaddr en0

__CAPGO_KEEP_0__ をサーバーから直接アプリを読み込ませるには、ファイルに別のエントリを追加する必要があります:

ipconfig

__CAPGO_KEEP_0__

Capacitor capacitor.config.ts __CAPGO_KEEP_0__

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'my-app',
  webDir: 'out',
  bundledWebRuntime: false,
  server: {
    url: 'http://192.168.x.xx:3000',
    cleartext: true
  }
};

export default config;

Capgoを使用する際には 正しいIPアドレスとポート番号を使用してくださいこの例では、デフォルトのReactポートを使用しています。

ここで、これらの変更をNativeプロジェクトにコピーできます:

npx cap copy

このコマンドは copy と似ていますが、 syncWebフォルダと設定のみをコピーし、Nativeプロジェクトを更新せずに実行します。 Android StudioまたはXcodeを使用してアプリを再度デプロイできます。その後、Reactアプリに何か変更を加えた場合、アプリは自動的にリロードされ、変更が表示されます! The

command is similar to but it will only copy over the changes made to the web folder

ご注意 新しいプラグインをインストールした場合、カメラなどの場合、ネイティブプロジェクトの再構築が必要です。これは、ネイティブファイルが変更されたため、オンザフライで行うことはできません。

注意してください。正しいIPアドレスとポート番号を使用する必要があります。上記のcodeブロックは、デモ用にデフォルトのReactポートを示しています。

Capacitor プラグインの使用

実際に使用するCapacitor プラグインについて説明しましょう。これは、前回何度か言及したことがあります。使用するには、次のコマンドを実行して簡単なプラグインをインストールできます。

npm i @capacitor/share

Share プラグインは何も特別なことはありませんが、ネイティブの共有ダイアログを表示します! これで、パッケージをインポートし、関数を呼び出すだけです。アプリのsrc/App.jsを次のように変更してみましょう。前述のように、新しいプラグインをインストールした場合、Sync操作を行い、再度アプリをデバイスにデプロイする必要があります。次のコマンドを実行してください。 share() src/App.js function redeploy

import React from 'react';
import { Share } from '@capacitor/share';

function App() {
  const share = async () => {
    await Share.share({
      title: 'Open Youtube',
      text: 'Check new video on youtube',
      url: 'https://www.youtube.com',
      dialogTitle: 'Share with friends'
    });
  };

  return (
    <div>
      <h1>Welcome to React and Capacitor!</h1>
      <p>
        <h2>Cool channel</h2>
        <button onClick={() => share()}>Share now!</button>
      </p>
    </div>
  );
}

export default App;

app

npx cap sync

ボタンを押した後、美しいネイティブシェアダイアログが実行されます!

react-capacitor-share

次に、iOSとAndroidでアプリがよりネイティブに感じられるようにするために、Capgoナビゲーションとトランジションを使用し、水平オーバーフローまたはクロップされたセーフエリアが原因となる一般的なiOSレイアウト問題を修正できます。

ネイティブフィーリングのUIとCapgoネイティブナビゲーションとトランジション

数年間、 Ionic を使用してクロスプラットフォームアプリケーションを構築してきましたが、Reactと統合することはハック的で、すでに Tailwind CSS.

を持っている場合、ほとんどの場合、価値がありません。React + Capacitorアプリでネイティブモバイルフィーリングを実現するには、WebのみのUIキットのようなKonsta UIではなく、Capgoプラグインを使用します。

  • @capgo/capacitor-native-navigation —ネイティブナビゲーションバー、iOSのLiquid Glassタブバー、Androidのブラーしたタブバーのスタイル。Reactルーターのルート状態を維持し、プラグインはネイティブのChromeを所有します。
  • @capgo/capacitor-transitions 〜Ionicスタイルのページ遷移とiOSのエッジスワイプバックをWebViewレイヤーで実現することができます。Ionic UIを採用する必要はありません。

両方をインストールする必要があります。

bun add @capgo/capacitor-native-navigation @capgo/capacitor-transitions
bunx cap sync

ネイティブのナビゲーションをCSSのインセットモードで設定して、ウェブコンテンツがネイティブのバーを尊重するようにします。

import { NativeNavigation } from '@capgo/capacitor-native-navigation';

await NativeNavigation.configure({
  contentInsetMode: 'css',
  animationDuration: 360,
  glass: {
    effect: 'liquidGlass',
  },
});

液体ガラスのタブバーをレンダリングします (iOSはシステムのレンダリングを使用し、AndroidはぼやけたWebViewのバックグラウンドを使用します)。

await NativeNavigation.setTabbar({
  selectedId: 'home',
  labelVisibilityMode: 'labeled',
  icons: true,
  colors: { dynamic: true },
  tabs: [
    { id: 'home', title: 'Home', icon: { svg: '...' } },
    { id: 'settings', title: 'Settings', icon: { svg: '...' } },
  ],
});

await NativeNavigation.addListener('tabSelect', ({ id }) => {
  navigate(`/${id}`);
});

アプリシェルにネイティブのページ遷移を追加します。

import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import '@capgo/capacitor-transitions';
import { initTransitions, setDirection, setupRouterOutlet } from '@capgo/capacitor-transitions/react';

initTransitions({ platform: 'auto' });

export function AppShell() {
  const navigate = useNavigate();
  const outletRef = useRef<HTMLElement>(null);

  useEffect(() => {
    if (outletRef.current) {
      setupRouterOutlet(outletRef.current, { platform: 'auto', swipeGesture: 'auto' });
    }
  }, []);

  const openSettings = () => {
    setDirection('forward');
    navigate('/settings');
  };

  return <cap-router-outlet ref={outletRef}>{/* routes */}</cap-router-outlet>;
}

ルーティングされたページをwrapします。 cap-router-outlet, cap-page、および cap-content、を呼び出します。 setDirection('forward') または setDirection('back') Capacitorライブアップデートの代替案を比較するページです。

Appflowの比較/移行のマーケティングコピーです。 Using @capgo/capacitor-native-navigation@capgo/capacitor-transitions.

セーフエリア

デバイスのセーフエリアをTailwind CSSで使用するには @capgo/tailwind-capacitor (公開日 tailwind-capacitor npmで safe-areas 機能やその他のCapacitor対応のTailwindプラグインを提供します。

bun add -D tailwind-capacitor

In src/index.css:

@import 'tailwindcss';
@plugin "@capgo/tailwind-capacitor/platform";
@plugin "@capgo/tailwind-capacitor/safe-areas";

機能を使用する pt-safe, pb-safepx-safe 代わりに env(safe-area-inset-*) 手作で。プロジェクトは活発に開発されています — React設定用に何かが欠けている場合、 GitHub にPRを開く.

iOSレイアウトの問題を修正する (ビュー ポート、セーフ エリア、水平オーバーフロー)

iOSでコンテンツが切り取られた、ずれた、または水平方向にスクロールできる場合、ビュー ポートタグを追加したり変更したりするだけでは通常解決しません。次のチェックを順番に実行してください。 overflow-x: hidden ビュー ポートメタタグが正しく適用されていることを確認する

ビュー ポートメタタグを追加する

内側 index.html iOSセーフエリアを1つのルートラッパーからのみ処理する <head>:

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />

単一のアプリシェルを作成し、セーフエリアのパディングをそこに適用する — 複数のネストされたコンポーネントに適用するのではなく:

すべてのページコンテンツを

html,
body,
#root {
  width: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

* {
  box-sizing: border-box;
}

.app-shell {
  min-height: 100dvh;
  width: 100%;
  padding-top: env(safe-area-inset-top);
  padding-right: env(safe-area-inset-right);
  padding-bottom: env(safe-area-inset-bottom);
  padding-left: env(safe-area-inset-left);
}

セーフエリアのパディングが複製されたヘッダー、モーダル、レイアウトラッパーは、UIが切り取られたり大きすぎるように見えることがよくあります。 .app-shell. Duplicated safe-area padding in headers, modals, and layout wrappers often makes the UI look cropped or too large.

With @capgo/tailwind-capacitor, you can express the same padding with utilities like pt-safe pb-safe px-safe on that single shell.

Set Capacitor iOS contentInset to never context: Live updates product page. Role: Short UI label or navigation item. Message key `live_update_dynamic_label_to` (Live Update Dynamic Label To).

first capacitor.config.tsIn contentInsetMode: 'css', prefer native inset disabled and let CSS (or Native Navigation’s)

const config: CapacitorConfig = {
  appId: 'com.example.myapp',
  appName: 'my-app',
  webDir: 'dist',
  ios: {
    contentInset: 'never',
  },
};

Mixing Capacitor’s automatic content inset with CSS env(safe-area-inset-*) Mixing Capacitor’s automatic content inset with CSS

真実のオーバーフロー要素を見つける

通常の容疑者は、固定ピクセル幅の要素を使用している 100vw, Tailwind w-screen, 固定ピクセル幅の要素、または大きい min-width.

Safari Web インスペクターで実行:

[...document.querySelectorAll('*')]
  .filter(el => el.scrollWidth > document.documentElement.clientWidth)
  .map(el => ({
    el,
    tag: el.tagName,
    class: el.className,
    scrollWidth: el.scrollWidth,
    clientWidth: document.documentElement.clientWidth,
  }));

Tailwindの場合、 w-screen を置き換える w-full 可能な限り 100vw / w-screen水平方向のオーバーフロー問題の多くは、

, 重複した安全エリアのパディング、または固定幅のコンテナ — ではなく、ビュー ポート メタタグ自体から

Capacitor is an excellent option for building native applications based on an existing web project, offering a simple way to share code and maintain a consistent UI.

__CAPGO_KEEP_0__は既存のWebプロジェクトに基づいて構築されるネイティブアプリケーションの優れたオプションであり、__CAPGO_KEEP_1__を共有し、UIの統一性を維持する簡単な方法を提供します。 Capgo最新の機能やバグ修正を常に利用できるように、リアルタイムの更新を追加することができます。

If you would like to learn how to add Capgo to your React app, take a look at the next article:

Keep going from Building Mobile Apps with React and Capacitor

Capacitorを使用している場合 Building Mobile Apps with React and Capacitor CI/CDの自動化を計画するには、Capacitor CI/CDと接続する Capgo CI/CD for the product workflow in Capgo CI/CD, Capgo Native Builds for the product workflow in Capgo Native Builds, Capgo Integrations Capacitor製品ワークフローにおけるCapgo統合 CI/CD統合 CI/CD統合の実装詳細については CI/CD統合の実装詳細についてはGitHubアクション統合 for the implementation detail in GitHub Actions Integration.

Capacitor アプリの即時更新

When a web-layer bug is live, ship the fix through Capgo instead of waiting days for app store approval. Users get the update in the background while native changes stay in the normal review path.

ウェブ層のバグが実行中の場合、__CAPGO_KEEP_0__ を通じて修正を配信するのではなく、アプリ ストアの承認待ちの日数を待つのではなく、ユーザーはバックグラウンドで更新を受け取り、ネイティブの変更は通常のレビュー パスに残します。

コンテキスト:Capgo マーケティング ウェブサイト。役割:サポート ドキュメントの説明文またはメタ ディスクリプション。見つける場所:コンポーネント GetStarted.astro。Capgo の製品/ブランド名と開発者用語をそのまま保存してください。メッセージ キー `instant_updates_for_capacitor_apps_description` (Capacitor アプリの即時更新の説明)。

マーティンから人間のサポートを受けます。

Capgo gives you the best insights you need to create a truly professional mobile app.