Cordova with Create-react-app
I have created a ReactJs app with create-react-app and then made the Production build with npm run build
. In my www folder created with Cordova I just copy all the files from the create-react-app's build folder and that's fine.
I want to know how do I hook into Cordova's events like for example:
function startApp() {
// your app logic
}
if (window.cordova) {
document.addEventListener('deviceready', startApp, false);
} else {
startApp();
}
For example I want to call the minified JS file inside startApp()
. Or is there any other workflow that can be used to make Cordova events work with react app.
A small example would be helpful.
Is it possible to use the build file at all and just use the React App directly inside Cordova? I am unsure how that would work given that there is Webpack settings which transpiles the ES6 code to ES5 and all.
I am new to Cordova and struggling with this integration aspect.
I have found to make the two work and will post here for anyone else looking for the same. There maybe other methods to do this , but this is what worked for me.
So basically we will create a Cordova App using(say) : cordova create testapp com.test.testapp testapp This will give me a Folder Structure as so:
testapp
--hooks
--platforms
--plugins
--www
--config.xml
Now inside the testapp folder we run : create-react-app teastappReact Which will add my react app inside testapp folder. Your react app will have a main index.js in the /src directory.
I the index.js make sure to wrap your main logic inside a function and then call the function along with Cordova object like so:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
const startApp = () => {
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
if(!window.cordova) {
startApp()
} else {
document.addEventListener('deviceready', startApp, false)
}
That should do now your app will have the Cordova instance along with Device objects like navigator.camera inside your app.
Also in your react apps index.html which can be found in the public folder copy the html from the index.html that you will find in the Codova www folder. Now we can delete all files from www folder. We will later manually or via a script copy all files from react apps build folder to Cordova www folder.
So my index.html would look something like below, notice the cordova.js file thats included as a script.
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<!--
Customize this policy to fit your own app's needs. For more guidance, see:
https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
Some notes:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src * data: content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!-- Latest compiled and minified CSS -->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="cordova.js"></script>
</body>
</html>
Finally in your react apps' package.json add the following line: .... "homepage": "../www" .... This will make sure your final build file is pointing at the right path. we can also add the following lines in your package.json build script.
"scripts": {
"start": "react-scripts start",
***"build": "react-scripts build && robocopy .\\build ..\\www /MIR",***
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"deploy": "npm run build&&gh-pages -d build"
}
It can be robocopy or cp-r based on the OS(Windows/Linux etc)..
We should have our Cordova app ready to be build with cordova build android/ios.
I solved the issue. Here's what I did in a step-by-step format for anyone looking for the solution:
- Copy/Create-a-new
React
project (created usingcreate-react-app
) just inside theCordova
app directory. - Clear all the contents of
www
folder ofCordova
app. -
cd
to React project folder (which you just copied/created) & openpackage.json
. - Before
dependencies
add"homepage": "./",
& inside scripts changebuild
to"build": "react-scripts build && robocopy .\\build ..\\www /MIR",
- Do
npm run build
in same (React
's) directory & go back to parent (Cordova
) folder thenbuild
andemulate
your project in desired platform. -
Bonus Tip: If you are using
<Router>
in your project change that to<HashRouter>
otherwise you'll see a blank display as nothing will get rendered to the screen.
I thought it was quite hard to find a complete guide how to fix this. I solved it like this, start to finish, to be able to run Create React App on an emulated Android device on Windows:
Start by creating a react app or use your existing app.
npx create-react-app my-app
https://github.com/facebook/create-react-app#creating-an-app
Then install Cordova:
npm install -g cordova
https://cordova.apache.org/docs/en/latest/guide/cli/
Create a new cordova application inside the my-app
folder in my case:
cordova create hello com.example.hello HelloWorld
Change directory to hello
or what you called your Cordova application.
cordova platform add ios
cordova platform add android
Run cordova requirements
to see what you need to build the project.
Since I'm on Windows I will only build it for Android in this example.
cordova platform remove ios
and confirm I have only Android with cordova platform ls
Install what you need based on cordova requirements
command. Since I had a fresh install I needed everything: Java Development Kit (JDK) 8, Gradle and Android SDK. Links can be found here:
https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#requirements-and-support
Or:
https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html
https://gradle.org/install/
https://developer.android.com/studio/index.html
Open Android Studio after it is installed. I choose a standard installation but it failed with the following warning:
Failed to install Intel HAXM. For details, please check the installation log: "C:\Users\Oscar\AppData\Local\Temp\haxm_log.txt" Intel® HAXM installation failed. To install Intel® HAXM follow the instructions found at: https://software.intel.com/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows Installer log is located at
C:\Users\Oscar\AppData\Local\Temp\haxm_log.txt Installer log contents: === Logging started: 2020-07-10 16:39:27 === This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.
I could however start the application anyway and add an Android Virtual Device (AVD) found under Configure.
I choose to add a Pixel XL
with R
system image.
However running cordova requirements
again I could see I needed an Android target with API level 28. R is level 30.
I therefore installed Pie
with API level 28 x86_64 and created a new virtual device.
Instead of opening AVD Manager
i opened SDK manager
and also downloaded the Android 9.0 Pie SDK.
Now everything looked good:
Then run cordova emulate android
to test the default Cordova application.
If it works it should look like this:
Change directory to my-app
.
Edit package.json
and add "homepage": "./",
before dependencies:
Thanks to @BlackBeard for that. Source: https://stackoverflow.com/a/46785362/3850405
Run npm run build
Clear everything in my-app\hello\www
then copy everything from my-app\build
to my-app\hello\www
.
Voilà:
If you don't edit my-app
package.json
and add "homepage": "./",
it will look like this:
Lessons learnt:
1.
If you are using <Router>
in your project change that to <HashRouter>
otherwise you'll see a blank display as nothing will get rendered to the screen. Works for both iOS and Android.
Source: https://stackoverflow.com/a/46785362/3850405
2.
You need a whitelist to allow URLs. From documentation:
By default navigations are only allowed to file:// URLs. To allow others URLs, you must add tags to your config.xml:
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/
Install like this:
cordova plugin add cordova-plugin-whitelist
Then edit config.xml
which is located in your application's root directory and add any of the following:
<!-- Allow links to example.com -->
<allow-navigation href="http://example.com/*" />
<!-- Wildcards are allowed for the protocol, as a prefix
to the host, or as a suffix to the path -->
<allow-navigation href="*://*.example.com/*" />
<!-- A wildcard can be used to whitelist the entire network,
over HTTP and HTTPS.
*NOT RECOMMENDED* -->
<allow-navigation href="*" />
Source: https://stackoverflow.com/a/30327204/3850405
3.
Even though you are using a whitelist you may still need to access an http API that does not support https. By default this is not allowed and can cause some real headache. Solve this as well by editing config.xml
and add the following under <platform name="android">
:
<edit-config xmlns:android="http://schemas.android.com/apk/res/android" file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application"> <application android:usesCleartextTraffic="true" /></edit-config>
Given that you do not browse to a URL any API call must specify the actual server. I normally use Axios so we only needed to add our server to the default URL. Example:
import axios, { AxiosPromise, AxiosRequestConfig, Method } from 'axios';
const getConfig = (url: string, method: Method, params?: any, data?: any) => {
const config: AxiosRequestConfig = {
url: 'http://192.168.1.249' + url,
method: method,
responseType: 'json',
params: params,
data: data,
headers: { 'X-Requested-With': 'XMLHttpRequest' },
}
return config;
}
export const sendRequest = (url: string, method: Method, params?: any, data?: any): AxiosPromise<any> => {
return axios(getConfig(url, method))
}
Then called like this:
const path = '/api/test/'
export const initialLoad = (number: number): AxiosPromise<InitialLoadDto> => {
return sendRequest(path + 'InitialLoad/' + number, 'get');
}
I created CLI for this.
npm i -g react.cordova
read more