Android hybrid with cordova and ReactJS
In the last post Android hybrid with cordova we discussed how to hybrid an Android App with cordova.
Now we’ll make a further step: use web framework ReactJS on web part of the hybrid App.
Create ReactJS project
First you should have Node.js installed.
Then execute npx create-react-app web
under directory of your hybrid App project.
Configure Webpack
Webpack 4 may not work well. Issue: Cannot read property ‘thisCompilation’ of undefined. So we use webpack 3.11.0 instead of the newest version.
-
npm install --save-dev webpack@3.11.0 babel-core babel-jest babel-loader node-sass css-loader sass-loader style-loader
-
Create webpack.config.js under App/web
- Modify App/web/package.json scripts.build to
"react-scripts build && ./node_modules/.bin/webpack --config webpack.config.js"
.
Web code
-
Move App/web/src/logo.svg to App/web/src/images.
-
We will not pack images in webpack, so we can make some changes in App/web/src/App.js, remove
import logo from './logo.svg';
. Change<img src={logo} className="App-logo" alt="logo" />
to<img src='images/logo.svg' className="App-logo" alt="logo" />
-
We need an html page to use the ReactJS code. Just copy App/web/public/index.html to output directory App/web/www, rename it to react.html. Add a line
<script type="text/javascript" src="bundle.js"></script>
under<div id="root"></div>
. -
Create some tool scripts to build and copy generated files to SD card of device. Check android-tools.py of CordovaDroid.
Native code
- Now we shall create a new native Activity to embed react.html. Create ReactActivity. Don’t forget add it to AndroidManifest.xml and make a new button in MainActivity to jump to ReactActivity.
- Create a new react.xml in App/src/main/res/xml which use react.html we just created.
-
Go to App project directory and execute
python3 android-tools.py
, select build -> qa -> debug (type 1,1,1). The script starts to build ReactJS project and Native App, then upload generated web files to SD card. -
Run App from Android Studio, click REACT button. You would get following page.