Ioniconf 2022 logo

Uniting our global community of Ionic developers and contributors. May 25, 2022.

DocsPluginsCLI
React

React & Capacitor

Build native mobile apps with web technology and React

01

Install Capacitor.

Add Capacitor to your project and create a config for your app

npm install @capacitor/core @capacitor/cli
npx cap init [name] [id] --web-dir=build
02

Build the Web App.

The compiled web assets will be copied into each Capacitor native platform during the next step.

npm run build
03

Install the native platforms you want to target.

AppleAndroid

Capacitor's native projects exist in their own top-level folders and should be considered part of your app (check them into source control).

npm i @capacitor/ios @capacitor/android
npx cap add android
npx cap add ios
04

Adding calls to Native APIs

With Capacitor installed, adding calls to native device features is as straight forward as calling other JavaScript methods

import React, {useState, useCallback} from 'react';
import { Geolocation } from '@capacitor/geolocation';

export default function GeolocationPage() {

  const [loc, setLoc] = useState(null);

  const getCurrentPosition = useCallback(async () => {
    const coordinates = await Geolocation.getCurrentPosition();
    setLoc(coordinates);
  }, [coordinates]);

  return (
    <div>
      <h1>Geolocation</h1>
      <p>Your location is:</p>
      <p>Latitude: {loc?.coords.latitude}</p>
      <p>Longitude: {loc?.coords.longitude}</p>

      <button onClick={getCurrentPosition}>
        Get Current Location
      </button>
    </div>
  );
}

Continue your Capacitor Journey.

This is only the beginning. Learn more about the Capacitor development workflow or using more native APIs .

The latest updates. Delivered monthly.

Capacitor is getting better every day. Sign up for a monthly email on the latest updates, releases, articles, and news!