Building Native Applications with Capacitor and ReactJS

eddiemuhoro

Edwin Muhoro

Posted on June 16, 2024

Building Native Applications with Capacitor and ReactJS

Introduction

In the ever-evolving landscape of software development, the demand for building native applications from web-based code has grown exponentially. Capacitor, a tool created by the team behind Ionic, offers developers a seamless way to create cross-platform native applications using their existing web technologies. In this article, we will explore how to incorporate Capacitor into a ReactJS project to build native mobile applications.

What is Capacitor?

Capacitor is a cross-platform native runtime that allows you to build web applications with JavaScript, TypeScript, or any front-end framework and then deploy them as native mobile apps or Progressive Web Apps (PWAs). It provides a simple and unified API to access native device features and functionalities such as the camera, geolocation, and storage.

Getting Started with Capacitor and ReactJS

To start using Capacitor with ReactJS, follow these steps:

Step 1: Set Up Your React Project
First, you need to create a new React project or navigate to your existing React project directory.



npx create-react-app my-capacitor-app
cd my-capacitor-app


Enter fullscreen mode Exit fullscreen mode

This command creates a new React project named my-capacitor-app and navigates into the project directory.

Step 2: Install Capacitor
Next, you need to install Capacitor core and the CLI (Command Line Interface). Run the following command in your project directory:



npm install @capacitor/core @capacitor/cli


Enter fullscreen mode Exit fullscreen mode

This command installs the core Capacitor library and the CLI, which you will use to interact with Capacitor from the command line.

Step 3: Initialize Capacitor
Initialize Capacitor with your project. This will create a capacitor.config.json file in your project directory.



npx cap init


Enter fullscreen mode Exit fullscreen mode

During initialization, you will be prompted to enter your app name and package ID (e.g., com.example.myapp). The capacitor.config.json file stores configuration settings for Capacitor.

Note: It’s important to change the package ID to something unique and meaningful for your project. The package ID should follow the reverse domain name notation (e.g., com.yourcompany.yourapp). This unique identifier is necessary for publishing your app on app stores and helps to distinguish your app from others.

Image description



? What is the name of your app? My Capacitor App
? What should be the Package ID? com.yourcompany.yourapp


Enter fullscreen mode Exit fullscreen mode

Step 4: Install and Add Platforms
Add the desired platforms (iOS, Android) to your project. This step prepares your project to be built and run on these platforms.
Install
npm install @capacitor/android
npm install @capacitor/android



npx cap add ios
npx cap add android


Enter fullscreen mode Exit fullscreen mode

This command creates the necessary folders and files for iOS and Android projects within your React project directory.

Step 5: Build Your React App
Before you can run your app on a device or emulator, you need to build your React app. This step compiles your React code into static files that can be served by Capacitor.



npm run build


Enter fullscreen mode Exit fullscreen mode

This command generates a build folder containing the static files of your React application. Building the project ensures that the latest version of your app is used when syncing with the native projects.

Step 6: Sync Your Project
After building your React app, sync your web code with the native platform projects. This step copies the built web assets into the native project folders.



npx cap sync


Enter fullscreen mode Exit fullscreen mode

The npx cap sync command ensures that the latest version of your web app is included in the native builds and updates any Capacitor plugins and dependencies.

Using Capacitor Plugins

Capacitor comes with a set of plugins to access native device functionalities. Here are a few examples:

Example 1: Using the Camera Plugin
Step 1: Install the Camera Plugin



npm install @capacitor/camera


Enter fullscreen mode Exit fullscreen mode

Step 2: Import and Use the Camera Plugin in your react code



import React, { useState } from 'react';
import { Camera, CameraResultType } from '@capacitor/camera';

const CameraComponent = () => {
  const [photo, setPhoto] = useState(null);

  const takePhoto = async () => {
    const image = await Camera.getPhoto({
      resultType: CameraResultType.Uri,
    });
    setPhoto(image.webPath);
  };

  return (
    <div>
      <button onClick={takePhoto}>Take Photo</button>
      {photo && <img src={photo} alt="Captured" />}
    </div>
  );
};

export default CameraComponent;


Enter fullscreen mode Exit fullscreen mode

Example 2: Using the Toast Plugin
Step 1: Install the Toast Plugin



npm install @capacitor/toast


Enter fullscreen mode Exit fullscreen mode

Step 2: Import and Use the Toast Plugin



import React from 'react';
import { Toast } from '@capacitor/toast';

const ToastComponent = () => {
  const showToast = async () => {
    await Toast.show({
      text: 'Hello from Capacitor!',
    });
  };

  return (
    <div>
      <button onClick={showToast}>Show Toast</button>
    </div>
  );
};

export default ToastComponent;


Enter fullscreen mode Exit fullscreen mode

Running the App on a Device

To run your app on a device, you need to open the native project in the respective IDEs.

iOS



npx cap open ios


Enter fullscreen mode Exit fullscreen mode

This will open your iOS project in Xcode. From there, you can run the app on a simulator or a connected device.

Android



npx cap open android


Enter fullscreen mode Exit fullscreen mode

This will open your Android project in Android Studio. You can then run the app on an emulator or a connected device.

Conclusion

Capacitor provides a powerful and easy-to-use platform for building native mobile applications using web technologies. By integrating Capacitor with ReactJS, you can leverage your existing web development skills to create robust, cross-platform native applications. This article covered the basics of setting up Capacitor in a React project, using plugins, and running your app on devices. With Capacitor, you can simplify your development workflow and deliver high-quality mobile experiences.

💖 💪 🙅 🚩
eddiemuhoro
Edwin Muhoro

Posted on June 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related