メインコンテンツにジャンプ
チュートリアル

Capacitorで純粋なReact.jsとモバイルアプリを構築する

Capacitorを使用してReact.jsのWebアプリケーションをネイティブモバイルアプリに変換し、Capgo Native Navigation、Transitions、iOSレイアウトのベストプラクティスを追加するガイド

Martin Donadieu

Martin Donadieu

コンテンツマーケター

React.jsとCapacitorでモバイルアプリを構築する

このチュートリアルでは、ReactとCapacitorを使用してモバイルアプリケーションを作成する方法を紹介します。最終的には、Capacitorを使用してReact.jsのWebアプリをネイティブモバイルアプリケーションに変換し、Capgo Native Navigation and Transitionsを使用してネイティブなフィールを追加できます。

Capacitorは、React.jsのWebアプリをネイティブモバイルアプリケーションに変換するための簡単な方法を提供し、React Nativeなどの新しい戦略を学ぶ必要はありません。

このプロセスには、数ステップしか必要ではなく、React.jsアプリが完全に機能するモバイルアプリケーションになるまで、すぐに実行できます。

Capacitorの概要

CapacitorJSはゲームチェンジャーです。どのWebプロジェクトでも簡単に統合でき、ネイティブのWebビューにアプリをラップし、ネイティブのXcodeとAndroid Studioプロジェクトを生成します。また、プラグインを使用して、カメラなどのネイティブデバイス機能にアクセスできます。

Capacitorは、ハッスルや急な学習カーブなしでネイティブモバイルアプリケーションを作成するための簡単な方法を提供します。APIとストリーミングされた機能は、プロジェクトに簡単に組み込むことができます。

React.jsアプリの設定

Reactアプリケーションを開始する最も簡単な方法を使用してみましょう。npmパッケージマネージャーを使用して、新しいReactアプリケーションを作成します:

npx create-react-app my-app

プロジェクトをネイティブモバイルアプリに変換するには、アプリの export が必要です。

We’ll come back to this in a moment. First, let’s understand how to integrate Capacitor into our React app.

Integrating Capacitor into Your React.js App

初期設定の手順は少し詳細になるかもしれませんが、その後、ネイティブアプリラッパーを更新することは、単にコマンドを実行するだけの簡単な作業です。 sync まず、CapgoとCapacitorを開発依存モジュールとしてインストールし、プロジェクト内にセットアップします。セットアップ中、名前とバンドルIDのデフォルト値に「Enter」を押してください。

First, we’ll install the Capacitor CLI as a development dependency and set it up within our project. During the setup, accept the default values for name and bundle ID by pressing “enter.”

最後に、プラットフォームを追加し、Capgoはプロジェクトルートに各プラットフォーム用のフォルダを作成します:

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

# 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

ios __CAPGO_KEEP_0__はCapacitorのことです。__CAPGO_KEEP_1__はCapacitorのことです。android ディレクトリは現在、React.jsプロジェクト内に存在します。

Androidプロジェクトにアクセスするには後で、 Android Studioをインストールしてください。 iOSの場合はMacが必要で、.

Xcode をインストールしてください。 次に、下記のように capacitor.config.json を更新してください。__CAPGO_KEEP_0__.config.jsonファイル

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

Run the build command and sync your project with Capacitor

npm run build
npx cap sync

The npm run build command will build your React.js project, while npx cap sync will align the web code in the accurate places of the native platforms so they can be executed in an app.

Now, with a little luck and no errors, your React.js app should be ready for launch on a device!

Building and Deploying Your Native Apps

iOSアプリの開発には Xcodeが必要です。 Androidアプリの開発にはAndroid Studio

The Capacitor CLI simplifies the process of opening both native projects:

npx cap open ios
npx cap open android

nativeプロジェクトがセットアップされたら、接続されたデバイスにアプリをデプロイするプロセスは、簡単です。

Android Studioの場合、すべての内容が読み込まれたら、接続されたデバイスにアプリをデプロイしてください。

Xcodeの場合、実機にアプリをデプロイするには、署名アカウントを設定する必要があります。そうすると、シミュレータではなく実機でアプリを実行できます。

すべてがうまくいったら、React.jsのWebアプリをネイティブモバイルアプリに変換することができます。

Capacitor Live Reload

モダンな開発フレームワークは、ほとんどの場合、ホットリロード機能を備えています。幸いにも、Capacitor も同様の機能を提供できます。 モバイルデバイス上で!

ローカルにホストされているアプリケーションを、Capacitor を使用して、ネットワーク上でライブリロード機能を実現できます。

まず、ローカルIPアドレスを決定する必要があります。Macの場合、ターミナルで実行してください。 ipconfig getifaddr en0 Windowsの場合、実行してください。 ipconfig IPv4アドレスを探してください。

この後、Capacitor をサーバーから直接読み込むように指示するために、パラメータを追加する必要があります。 capacitor.config.ts ファイル:

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

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

export default config;

正しいIPアドレスとポート番号を使用してください。次に、 npx cap copy これらの変更をCapgoのネイティブプロジェクトに適用するには

Android StudioまたはXcodeを使用してアプリを再度デプロイすると、Reactアプリの変更は自動的にロードされ、アプリ内で表示されます!

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

Capacitor プラグインの使用

Capacitor プラグインを使用する方法をご紹介します。簡単なプラグインをインストールしてみましょう。 Share プラグイン、ネイティブの共有ダイアログを提示します。

npm i @capacitor/share

使用するには、パッケージをインポートし、関連する share() アプリの関数を呼び出してください。 App.js:

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

function ShareButton() {
  const share = async () => {
    await Share.share({
      title: 'React App',
      text: 'Visit this React App',
      url: 'http://localhost:3000',
      dialogTitle: 'Share with...'
    });
  };

  return (
    <button onClick={share}>
      Share
    </button>
  );
}

export default ShareButton;

After installing a new plugin, please sync your React project again using npx cap sync.

Next, you can make the app feel more native on iOS and Android with Capgo navigation and transitions, and fix common iOS layout issues that cause horizontal overflow or cropped safe areas.

Native-feeling UI with Capgo Native Navigation and Transitions

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

For a native mobile feel in a React + Capacitor app, use Capgo plugins instead of web-only UI kits like Konsta UI:

Install both:

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

バールバームコトにバールバームコトに当前にらだ。バールバームコトに当前にらだ。

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

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

バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。

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>;
}

バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 cap-router-outlet, cap-pageバールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 cap-contentバールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 setDirection('forward') バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 setDirection('back') バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。

バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 Using @capgo/capacitor-native-navigation バールバームコトにコンタイントにバールバームコトに当前にらだ。バールバームコトにバールバームコトに当前にらだ。 Using @capgo/capacitor-transitions.

安全なエリアにTailwind

Tailwind CSSのデバイス安全エリアを使用するには @capgo/tailwind-capacitor (__CAPGO_KEEP_0__として公開) 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";

Reactアプリケーションで使用する pt-safe, pb-safepx-safe の代わりに env(safe-area-inset-*) 手動で散らかすのではなく open a PR on GitHub.

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-shellWith

With @capgo/tailwind-capacitor, その同じパディングをユーティリティのように表現することもできます。 pt-safe pb-safe px-safe その単一のシェル上で。

Capacitor iOS contentInsetnever 最初

In capacitor.config.ts, 自然のインセットを無効にして、CSS (またはネイティブナビゲーションの) が安全なエリアを所有することを優先します。 contentInsetMode: 'css'__CAPGO_KEEP_0__の自動コンテンツインセットとCSSのパディングを組み合わせることは、ダブルスペースの原因となる一般的な問題です。

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

Capacitorの自動コンテンツインセットとCSSのパディングを組み合わせることは、ダブルスペースの原因となる一般的な問題です。 env(safe-area-inset-*) 実際にオーバーフローしている要素を探してください

protectedTokens

通常の原因は、 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-screenw-full できる場合。多くの水平オーバーフロー問題は、 100vw / w-screen, 重複した安全エリアのパディング、または固定幅のコンテナ — ではなく、ビューポートメタタグ自体から来ています。

結論

Capacitorは、既存のWebプロジェクトに基づいてネイティブアプリを構築するためのシームレスな手段を提供し、簡単な方法でcodeを共有し、UIの統一性を保つことができます。

Thanks to technologies like Capacitor, building mobile applications from React.js web apps has never been easier. Take your web development skills to the next level by crafting impressive native mobile apps. Happy coding!

アプリ開発プロセスを高速化する方法についてさらに詳しく知りたい場合は、 sign up for a free account today.

Keep going from Building Mobile Apps with Pure React.js and Capacitor

If you are using Building Mobile Apps with Pure React.js and Capacitor to plan native media and interface behavior, connect it with Using @capgo/capacitor-live-activities for the native capability in Using @capgo/capacitor-live-activities, @capgo/capacitor-live-activities for the implementation detail in @capgo/capacitor-live-activities, Using @capgo/capacitor-video-player for the native capability in Using @capgo/capacitor-video-player, @capgo/capacitor-video-player @capgo/capacitor-video-playerの実装詳細について Using @capgo/capacitor-native-navigation Using @capgo/capacitor-native-navigationのネイティブ機能について

リアルタイムの更新をCapacitorアプリに提供

ウェブ層のバグが生じた場合、Capgoを通じて修正を配信し、アプリストアの承認待ちの日数を待たずに済みます。ユーザーはバックグラウンドで更新を受け取り、ネイティブの変更は通常のレビュー経路を通じます。

Get Started Now

ブログの最新記事

Capgoは、プロフェッショナルなモバイルアプリを作成するために必要な最良の洞察を提供します。