Learn to Build Cross-Platform Apps with React and Cordova – TUTORIAL

Building and maintaining multiple apps for multiple platforms (iOS, Android, Web) is quite a challenging and consuming task. That’s why these days we have multiple cross-platform frameworks that help us in building Hybrid Apps, using only a single codebase.

Today, the cross-platform framework we’ll be using is Cordova which is very fast & easy to use. And on top of that, we’ll be using a Frontend Framework called React.js. As we go further into this tutorial you will be able to appreciate how powerful and robust this combination would turn out to be

Before moving ahead, let’s get a better understanding of the technologies we’ll be using in this tutorial

What is Cordova?

phonegap cordova logo

Apache Cordova is an Open Source derivative of what used to be called Adobe PhoneGap. For our purposes, both of these are the same framework although you might still find some articles/information on the internet that refer to it as Adobe PhoneGap. However, from this point on I’ll simply refer to it as Cordova

Cordova as a framework helps us in building Android, iOS, and Windows Phone (now deprecated) apps, using HTML/CSS/JS source code. Basically, the thing to note is you can convert almost any standard web application to a Cordova app with almost no effort.

Not just that, the exciting part about Cordova is that it supports access to Native Mobile Features such as Geo Location (GPS), Camera, Vibration Sensor, etc. And it provides access to these features using Cordova Plugins which we can install as needed.

What is React.js?

reactjs logo

To be clear, React.js has nothing to do with Cordova or Mobile applications in any way. It’s simply a Web Framework, that helps us in efficiently build the frontend of websites. There are many such front-end web frameworks that do the same job ( Such as Vue.js & Angular.js ) But we’ll be using React.js as it is currently the most popular and is a lot more beginner friendly.

If you are still confused about how we’ll be integrating React.js into Cordova. The Flow is quite simple

  • We first make a normal React.js website in a separate project folder without even considering Cordova
  • Then we compile the React.js code we have written and we get the website in the form of HTML/JS/CSS
  • Then we simply take this generated HTML/JS/CSS and put it inside the Cordova project
  • We then add Cordova Plugins as needed to the app
  • Then we compile it to generate the APK!

React Native vs Cordova + React

If you have heard anywhere about a framework called React Native then you might question that “Aren’t they essentially the same thing?”. These types of questions arise from misconceptions such as “Since Both of them use React & Both of them help in making mobile applications, they are the same thing”.

However, that is not completely true. Let’s have a look at how they compare and which one you should use.

  • Cordova apps simply display the website for what it is by using something called WebView (essentially it creates a mini-browser and runs the app as a website in it) 
  • React Native on other hand, actually compiles the code into Native Android/iOS components and runs the app as if it were a completely Native application. This can provide some serious performance benefits and increase the responsiveness of your app
  • Another major difference is that we don’t need to change a lot of the Website code to make a Cordova app, however, to make a React Native application, we can’t just simply paste in the HTML/CSS/JS and expect it to work, there are considerable differences between React Native code and a normal React web application 

What will we build in the Tutorial?

The best way to learn something is to “Learn by Doing” and that’s why we’ll be building a small application in this tutorial. What better way to learn than to build a Game? Let’s get started by building a simple version of Rock, Paper, and Scissors.

Here’s a little sneak peek of the app to get you excited:

final react cordova app demo

Part 1: Installing the Essential Tools for Cordova + React.js Project

To build a Cordova application, we first have to install some essential tools, since most of the people reading would be using Windows, I’ll mainly focus on that. However, don’t be afraid if you have a macOS/Linux since most of the procedures should be pretty similar

Node.js

nodejs logo

If you went through the website of Cordova you might’ve noticed that there is no .exe file or anything that allows you to “install” Cordova, because it’s only available as a package on Node Package Manager, and to use that you have to install Node.js first.

To install Node.js, simply go to their website ( https://nodejs.org  ) and download the latest stable version ( Which, as of writing this article is 16.16.0 LTS ) just follow the on-screen installation instructions, and voila! You just installed Node.js

Cordova

As we discussed, it’s only possible to install Cordova on something called NPM ( Node Package Manager ). Now that we have Node.js ( and NPM ) installed, we can install Cordova on our machine by simply running the following command on your CMD or Powershell

npm install -g cordova

What this command essentially does is, installs the “Cordova” package globally (accessible from anywhere in the system ), and that’s what the -g flag signifies

Tip if there’s some error running this command, ( such as ACCESS DENIED ) try running it by opening the CMD or Powershell as RUN AS ADMINISTRATOR, as it might require admin privileges to globally install Cordova

Android Studio

android studio logo

Since we’ll be building android apps, we must have the Android SDK installed, to do that we first have to install Android studio from its official website. (Similar instructions, download the .exe file for windows, and follow the on-screen instructions to install).

After installing Open Android studio and clicking on SDK Manager, then you’ll get a list of SDK Versions that you can install, The Latest Cordova version supports the Android 12 SDK, so select it and click on apply, the installation procedure should look something like this 

android studio component installer

After Installing the SDK, we have to install SDK Command-line Tools and Android SDK Tools, to do that, go to Home of Android Studio -> SDK Manager -> Tools  and Select both of the options (Deselect Hide Obsolete Packages) 

android studio sdk settings

 Click on apply, The installation procedure should look like the following 

android studio sdk installation

Now, we need to install the SDK Build-tools ( The one which Cordova Supports is 30.0.3), To install that simply go to SDK tools, select Show Package details, and install the 30.0.3 Version.

Java Development Kit (JDK) 

jdk logo

For Android development Cordova Requires you to have something called Java Development Kit or JDK, this is because JDK has some essential libraries and tools, that help Cordova in compiling the Android App

For Using Cordova 10.0.0+ ( The latest version ) We have to install JDK version 8, To do that simply visit Oracle’s official website for JDK, create an oracle account and simply download the installer from there. In a few minutes, you should have JDK Installed on your Computer

Gradle 

gradle logo

Gradle is a build automation tool that Cordova requires for compiling/building our applications. To install Gradle, Simply visit their website and download the installer, and follow the instructions. 

Visual Studio Code (Optional) 

This part is completely optional as you can use any favorite IDE of yours. If you don’t know what an IDE is, it’s simply a program/software which makes writing code easier by providing advanced features such as Syntax Highlighting, detecting the errors before we even execute the program, etc. If you haven’t used an IDE before I’d recommend you install Visual Studio Code as that’s what most people prefer and that’s what we’ll be using in this tutorial as well.

If you have any problems during installation, you can read the  in-detail installation guide on the official website of Cordova

For now, do not worry about installing React as we can just use a single-line command to automatically create a basic React.js project and install React for us

Part 2: Setting Up The React.js Project

Recall the flow with which we’ll be building the app, the first step is to build it as a React Project without considering Cordova and then generate the HTML/CSS/JS from it so that we can use it in Cordova

To create a React.js project, we run the following command 

npx create-react-app <folder-name>
create react app commandline

You will then receive a prompt confirming whether to create the app or not, press y to proceed and within a few minutes your app should be created in rps-web or whatever folder you chose 

Open the folder rps-web inside Visual Studio Code

You should then see a lot of files/folders already present in the project. Let’s have a look at them and try to understand the purpose of all the files present 

reactjs project structure

node_modules folder

This is probably the first thing you would have noticed in the project, this is a folder that has all of the installed Packages for the project. However, we will not modify/create anything in this folder as it is managed entirely by Node Package Manager ( NPM ), and modifying this folder directly can cause issues in our project.

public folder

As the name says, all of the files inside this folder are public to the users and they are all hosted whenever the project is run

Mostly we’ll be putting images and other static content here

index.html file

Notice how there is only one single index.html file inside the public folder and no other CSS/javascript files. That’s because React.js works on the principle of building Single Page Applications. This means there’s only one single index.html file for any website no matter its size. Additional styling/javascript is automatically injected by React as needed

Src folder

As the name suggests, it’s the Source code folder. This is the part where we’ll be writing most of our code.

package.json & package-lock.json

These files contain the ‘list’ of packages we installed on our application and other related information.

Now that we had an overview of the folder structure, let’s start the React Application by running the following command 

npm start

This should start the react project and open up a new tab in your browser

reactjs default page

Part 3: Creating The React App 

As discussed, we’ll be writing most of our code in the App.js file, so let’s first open that up, and remove all of the code that’s already present there so that we can start from scratch and have a better understanding of what’s going on

Now let’s start by creating the App component

import "./App.css";
function App() {

}
export default App;

Hmm.. something’s weird though. How can we import a .css file inside a javascript file? You might ask. Well that’s because React uses something called Webpack underneath, this makes it possible to import all sorts of stuff from .css to image files to .svg almost anything as a normal javascript import 

Looking at the final product you might get an idea of what the HTML would look like. So let’s add a few elements to the homepage. 

<div className="main">
      <div className="header">
        <div>Rock Paper Scissors 👊</div>
      </div>
      <div className="body">
        <div>Choose Your Option</div>
        <div className="options">
          <Link to="/result/Rock" className="option-container">
            🪨
          </Link>
          <Link className="option-container" to="/result/Paper">
            📄
          </Link>
          <Link className="option-container" to="/result/Scissors">
            ✂️
          </Link>
        </div>
      </div>
    </div>

If you only know about HTML and are wondering how we are putting HTML inside Javascript and why we are using className instead of class? Well, that’s because it’s not exactly HTML. But something called JSX ( JavaScript XML ) You can learn more about it here.

Do not worry about the <Link> elements for now as we’ll be learning about them when we’ll be using React Router

If you notice the final app, you might see that there are not one but 2 pages. One is the Home Screen and the other is Results Screen

To make the Result Screen, let’s first create a new file called ResultScreen.js inside the src/ folder and add the following code to it

import "./App.css";

function ResultScreen() {
}

export default ResultScreen;

Now the way that it will work is,

  • The user will pass his choice onto the Result Screen
  •  We randomly generate the computer’s choice
  •  Compare them both to calculate the result

Let’s follow all the three steps above

Step 1

  let { userChoice } = useParams();

For now, don’t worry about the useParams() function and just assume that it somehow gets the choice that the user clicked on the homepage

Step 2

let possibleComputerChoices = ["🪨", "📄", "✂️"];
let possibleComputerChoicesText = ["Rock", "Paper", "Scissors"];
let computerChoiceIndex = Math.floor(Math.random() * 3);
let computerChoiceText = possibleComputerChoicesText[computerChoiceIndex];

Here we use a randomization function called Math.random() to randomly choose an index between 0 and 2 so that we can map it to the corresponding element in possibleComputerChoices & possibleComputerChoicesText

Step 3

 let userWon = false;
  let draw = false;

  if (userChoice === computerChoiceText) draw = true;
  if (userChoice === "Rock" && computerChoiceText === "Scissors") {
    userWon = true;
  } else if (userChoice === "Paper" && computerChoiceText === "Rock") {
    userWon = true;
  } else if (userChoice === "Scissors" && computerChoiceText === "Paper") {
    userWon = true;
  }

In this code, we are just adding a few if/else statements to determine if it was a draw or if the userWon

Depending on the above variables, we can now write the HTML (or JSX ) of ResultsScreen

<div className="main">
      <div className="header">
        <div>Rock Paper Scissors 👊</div>
      </div>
      <div className="body">
        <div className="computer-choice">
          Computer's Choice : {possibleComputerChoices[computerChoiceIndex]}
        </div>
        <div className="result-text">
          {draw
            ? "Draw"
            : userWon
            ? "Congrats! you beat the computer"
            : "Oops!"}
        </div>
        <Link className="reset-button" to="/">
          Try Again!
        </Link>
      </div>
    </div>

Something new to note here would be that we can write Javascript code inside the JSX by wrapping the javascript inside curly brackets {}

Now that we have both the pages ready, it’s time to Link them. For our app, we’ll be needing two <LInk/>’s 

  • From the HomePage to ResultScreen ( User clicks a Rock, Paper, Scissors choice )
  • From Result Screen to HomePage ( User clicks on Try Again! )

To add them first we have to install a package called react-router-dom, this will help us in adding routing to our page

To install react-router-dom, run the following command

npm install react-router-dom

Now to effectively use the <Link>’s we’ve added above  in our code, we have to define all of the routes present in our app by adding the following code to the main index.js file 

<Router>
      <Routes>
        <Route path="/" element={<App />}></Route>
        <Route path="/result/:userChoice" element={<ResultScreen />}></Route>
      </Routes>
    </Router>

If you get any error while running the code, make sure that all of the imports are working and that you have added the import statement for “react-router-dom”

By Adding these routes, we complete our app on the web!

Now if you run the website it might look pretty ugly, so let’s add some CSS inside the App.css file to give it a brand-new look

.main {
background-color: indianred;
height: 100vh;
}
.header {
  font-size: 40px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  padding: 10px;
  background-color: lightcoral;
}

.body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  height: 100%;
  font-weight: bold;
}

.options {
  display: flex;
  margin: 30px;
}
.option-container {
  border: 2px solid white;
  padding: 20px;
  font-size: 50px;
  margin: 10px;
  border-radius: 10px;
  text-decoration: none;
}

.option-container:hover {
  background-color: white;
}

.reset-button {
  border: 2px solid white;
  padding: 10px;
  font-size: 20px;
  margin: 20px;
  border-radius: 10px;
  text-decoration: none;
  color: black;
  background-color: white;
}

Now the website should look something like this 

final reactjs website

Adding Support For Cordova

The last step is to make a few changes to the index.js file 

document.addEventListener("deviceready", startApp, false);
function startApp() {
 
  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(
    <React.StrictMode>
      <Router>
        <Routes>
          <Route path="/result/:userChoice" element={<ResultScreen />}></Route>
          <Route path="*" element={<App />}></Route>
        </Routes>
      </Router>
    </React.StrictMode>
  );
}

Basically to add support for Cordova we need to make sure that the React App is started only after Cordova Device is finished loading.

To achieve that we have to follow 2 steps

  • Wrap the render function inside a new function called startApp()
  • Then add an EventListener() that calls the function startApp() as soon as Cordova is finished initialization

Part 4: Exporting the React App

To export the React App as HTML/CSS/JS so that we can use it in Cordova, we have to run the following command 

npm run build

If everything went alright you should see something similar to the following output

Note the locations of exported files

  • The 2 Javascript files are inside the build/static/js folder
  • The CSS file is inside the build/static/CSS folder
  • The main and only index.html file is inside the public folder

Part 5: Setting Up The Cordova Project

To create a new Cordova project, we run the following command

cordova create <folder name> <package name> <app name>

The above command takes in 3 parameters, out of which Folder Name & App Name should be pretty obvious to you. If you don’t know what a Package Name is, it’s a Unique Identifier for any app, mainly used by the App store and Play Store to identify apps that have the same name. A Standard package name is usually of the format com.companyname.appname

In our case, the command would be 

cordova create rps com.curiousco.rockpaperscissors RPS

After creating the app a new folder called rps is created, let’s open that folder in VSCode and try to understand the files inside it

file structure of cordova project

config.xml is the Cordova configuration file that has all the essential details about the app such as App Name, Package Name, Description, etc. For the most part, we won’t be touching this file as it is managed by Cordova itself

.gitignore is NOT related to Cordova in any way, it’s a special file used by GIT (If you don’t know git, it’s a powerful & popular version control system used to keep track of changes in the project, you can learn more about it here ) to keep track of the files to ignore and not upload to the git repository

www folder is the part of the project where most of the code will be written. If you open the www subfolder, you’ll see the following structure

www folder for cordova project

You might find that this structure resembles a standard HTML/CSS/JS website and the code is neatly segregated into 3 folders

CSS folder holding all of the stylesheets

img folder having all of the images

js folder having the Javascript

index.html is the main entry point for the application, this is the file that is run as soon as the user visits our app.

Before getting into the code, we have to let Cordova know what platforms we require the app for. For this tutorial we will be building an Android app only as compiling an iOS app requires iOS SDK and that is available only on macOS

To add the Android platform on Cordova simply run the following command 

cordova platform add android

If everything went well, the command should return the following output 

add andriod platform cordova

Now let’s start by building a .apk file for the project

To do that, we simply have to run 

cordova build android 

Be patient as this process can take a few minutes depending on your computer. If everything goes fine you will see a message “BUILD SUCCESSFUL” and will get the location of the .apk file on your computer.

Installing an Emulator 

Even though you can simply transfer the .apk file to test it. You will sooner or later realize that it is a tedious process to keep transferring/installing the app over and over again. Do not worry as there is a solution for it, and it’s called Emulators.

An emulator is software that is designed to run Another Operating System on our device. Android Studio by default provides us with the required tools to create and run an Android Virtual Device / Android Emulator

To Create an Android Virtual Device ( AVD ), simply go to the home of Android Studio and select Virtual Device Manager

android studio home screen

Then, click on Create Device and you should see a bunch of options as shown below 

android emulator configuration

Select the type of Device ( Phone, Tablet, Android TV, Android Watch ) you want to emulate and after selecting the configuration your Virtual Device should be created. To test it simply click on Run and wait for the device to boot

android emulator home screen

Congrats! Your android emulator is now installed and working!

Running the App on Emulator

Cordova can, by default, detect all of your Android Virtual Devices without any additional setup. To run the app on your emulator run the following command 

cordova emulate android

You should now see the following app running on your Emulator 

cordova app on android emulator

Part 6: Adding the React.js Exports to Cordova

Now that we have the emulator up and running, the only thing we have to do is insert the React Exported files into the www folder

The process should be very simple

  • Delete All The files inside the www/CSS and www/js folder
  • Delete The index.html file inside the www folder
  • Insert the React Exported index.html inside the www folder
  • Insert the React Exported js and CSS files inside www/js and www/CSS folders respectively

Then we need to make a few changes to the index.html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="./logo192.png" />
    <link rel="manifest" href="./manifest.json" />
    <title>React App</title>

    <script defer="defer" src="./static/js/main.b94de806.js"></script> 
 

 
 

 

<!-- Changes Made here -->
<script src="cordova.js"> </script>
<!-- -->

 

    <link href="./static/css/main.aef657e4.css" rel="stylesheet" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

 

The only thing we have to do is to add the cordova.js file and That’s it you are done with importing the app to Cordova, to test it simply run the following command 

cordova emulate android

You should now see an emulator open up with an app looking very similar to the final product

Part 7: Exporting the Cordova App to Android APK

After testing the app on the Android emulator it’s finally time to export it to an APK file so that we can distribute the app to various platforms such as Google Play Store

To generate the .apk file, run the following command inside your Cordova project folder

cordova build android

If you have everything set up properly the apk file should be generated within a few minutes 

Note: initial builds can take anywhere between 10-20 minutes on slow computers, so please be patient

Part 8: Exporting the Cordova App as iOS .ipa

If you are running macOS and have the iOS SDK installed, you can build the same project for iOS without making any changes in the code

ios

To build the project as an iOS .ipa file, run the following command inside the Cordova Project folder

cordova build ios

Within a few minutes, the .ipa file should be generated which you can share with your friends and even Publish to the App Store!

Conclusion

Congrats on coming this far and finishing the tutorial and building your very first Cordova + React Application! A good way to move forward would be to learn more about Cordova Plugins on their official website and add a few of them to the current application to extend its functionality. To solidify the concepts and have some fun, you can try to make a Cordova + Angular or Cordova + Vue.js app and see how it compares with a Cordova + React app. That way you can get an in-depth understanding of this tutorial. If you liked this article and learned something new today, do share it with your friends!