Aha! How to build slick user interfaces in React Native! Or… What is the Bootstrap equivalent for React Native?

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone.

Welcome budding React Native developer. If you’re like me and come from a web development background, and are fumbling around trying to figure out how to build slick stylized user interfaces in React Native, you’ve come to the right place!

For the past two days I was stuck trying to figure out how to simply drop in some style into my React Native app like you can easily do with Bootstrap in the web development world. While I was able to find half a dozen or so libraries for adding style to <Text>, <Button>, and <Input> components, I couldn’t really find any full featured UIKits that included things like TabBars/BottomNavigationBars, and make easy slick sliding navigation between screens.

Well you’ve waited long enough, here is what I’ve discovered. What you really need are two (or three) libraries. First, you need the “React Navigation” to handle navigation:

$ npm install react-navigation

Second, you need react-navigation-material-bottom-tabs for adding in your slick sliding/swipable TabBar/BottomNavigationBar:

$ npm install react-navigation-material-bottom-tabs

Last, go ahead and play around with any of the available component libraries for React Native. There are a whole bunch to choose from for adding simple styles to your components. The scarce resource is React-Navigation + React-Navigation-Material-Bottom-Tabs. That’s where the real UI magic comes in! So far I haven’t found any alternatives that allow you to swipe between screens and integrate with the tab bar. So I hope my research helps!

Also, I wasn’t able to find this in any of the React Native books that I looked at, or on the React Native website for that matter. So big shout out to Unsure Programmer on YouTube for his excellent tutorial on implementing swipeable bottom tab navigation in React Native!

And here are the Top 5 component styling libraries rated by stars on GitHub:

  1. UI Kitten
  2. Paper
  3. React Native Material Kit
  4. React Native Material UI
  5. Nachos UI
 

How to Load an Image Component in React Native

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone.

Greetings intrepid JavaScript developer(s)! Quick post here regarding how to load images in React Native. I personally have been following along with the official React Native Quickstart guide teaching myself React Native recently, and have found that some of the examples do not work when running the apps using the React Native CLI as opposed to running them using the Expo CLI. So, here’s a code snippet on how to load an image component in React Native =>

// NOTE: In the same directory as your App.js file,
// create a new folder called "assets", and place
// your image file (.jpg) in that directory.
import React, { Component } from 'react';
import { Text, View, Image } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<Text>RENDER AN IMAGE...</Text>
<Image source={ require('./assets/supersweetimage.jpg') } />
</View>
);
}
}
export default App;
view raw App.js hosted with ❤ by GitHub
 

Unable to load script. Make sure you’re either running a Metro server (run ‘react-native start’) or that your bundle ‘index.android.bundle’ is packaged correctly for release.

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone.

Hello there dear internet friend and React-Native developer. If you happen to have been stuck on this awful error message for hours, I’ve got the solution for you! Well… at least I have the solution for me, hehe.

Okay, so my problem ended up being that the version of NodeJS I was running on my Windows Machine, Node 13, was not compatible with Metro server. Therefore Metro server would continually crash over and over again. For hours I wasn’t even able to get to hello, world. Ouch! Maybe you happen to be running into the same thing?

Anyway, here’s the solution. Downgrade from version 13 of NodeJS down to version 10. Don’t bother with Version 12, it will still crash. What you want is version 10.

  1. Go to ‘Add or remove programs’
  2. Search for Node.js, and Uninstall
  3. Visit nodejs.org and download version 10 of NodeJS in .msi format
  4. Install NodeJS version 10
  5. Close your Command Prompt, start over, and voila! Simply follow the standard React Native CLI Quickstart Guide and everything should work as expected.
 

Can You Use JavaScript localStorage as a Database for Your Apache Cordova or PhoneGap Application?

Over the past few months I’ve been programming primarily using Apache Cordova, and currently happen to be starting a new project which will require a bit of data persistence. I know that I can probably ship the production version of the app extremely quickly if I go with simple JavaScript localStorage for the in-app database. However, there are some downsides to this, and that’s what I’d like to talk about in this blog post.

Before digging into this topic tonight, I knew that data stored using localStorage may not be as persistent as other options. But what I didn’t know, was how persistent is it? Will a user clearing his or her web browser cache cause my app to lose data? What about clearing cached data for all applications under settings? How about specifically clearing cached data for my app specifically? Or clearing all data for my app specifically? Well now after a little experimentation and research, I think I have a pretty good answer!

  1. Clearing “browsing data” on Chrome for Android will not cause your Cordova app to lose localStorage data.
  2. Clearing “cached data” for all apps under Settings on Android will not cause your Cordova to lose localStorage data either.
  3. Selecting the “clear cache” option for your app specifically will not cause your Cordova app to lose data.
  4. SELECTING THE “CLEAR DATA” OPTION FOR YOUR APP SPECIFICALLY WILL CAUSE YOUR CORDOVA APP TO LOSE DATA.

So there you have it. There are the results of my non-scientific investigation into JavaScript localStorage and Apache Cordova. Your Cordova app’s data should be safe using localStorage as long as users do not go out of their way and select the “clear data” option for your app under Settings>Storage>Internal-Shared-Storage>Apps>YourCordovaApp. If you happen to be developing an Apache Cordova or PhoneGap application for Android, choosing JavaScript localStorage for your in-app database should be fine.

With that being said… JavaScript localStorage IS NOT A VIABLE OPTION FOR iOS APPLICATIONS. I’ll repeat that again… JavaScript localStorage IS NOT SUITABLE FOR iOS APPLICATION DEVELOPMENT WITH APACHE CORDOVA OR PHONEGAP.

Saved that abrupt zinger for the end huh?!? Yup, there’s the plot twist. Turns out, iOS will clear out your localStorage whenever it feels like it (apparently whenever memory is low). So if it isn’t a big deal if your localStorage gets cleared out, then you can go ahead and use it for iOS application development as well. But if data persistence is a really important feature of your app, make sure to stay clear of JavaScript localStorage when developing iOS applications with Apache Cordova or PhoneGap.

Things were looking good there for a moment, right? JavaScript localStorage for the win! For most use cases localStorage is still probably okay for iOS. However, for this latest untitled side project data persistence is going to be extremely important. So for Version 0, it looks like I’m just going to be rolling out on Android. Will have to tackle iOS another day using something a little more sound like the cordova-sqlite-storage plugin. Maybe that will make for an appropriate follow up post; // the end

 

Cameron Moorehead’s Tutorial on Coding Your Own Modals in ReactJS

This is going to be a pretty quick blog post tonight for my own personal reference. Normally I would like to post my own little tutorials and bug fixes for various programming related topics, but for this post I really just want to bookmark Cameron Moorehead’s excellent tutorial on coding your own modals in ReactJS.

In the past I have used other developers modals in my projects by downloading various plugins. However, in the last version of my app, MoneyPhone, the modal I used caused some nasty issues whenever I needed to transition to a new page in the app using Turbolinks. And since the workaround I ultimately came up with was quit ugly, this time around I’m going to give creating my own simple modals a try!

So, big shout out to Cameron Moorehead! I think I could have figured out how to accomplish this on my own, but his tutorial will probably save me at least a full day of fumbling around with CSS. So without further ado => Implementing a Simple Modal Component in React

 

Uncaught TypeError: this.setState is not a function at XMLHttpRequest.httpRequest.onreadystatechange

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

this.setState not a function at XMLHttpRequest? Here’s the quick fix you are looking for friend…

var that = this; that.setState({/* json goes here */});

Essentially, that’s all there is to it. The problem is when onreadystatechange fires asynchronously, this will no longer reference the same “this”. So, we simply create another variable called “that” which references the “this” we want. I know all of this gobbledygook about “this” and “that” and whatnot problably is not making any sense. So here is a little example code for reference:

handleRefreshData(paramOne, paramTwo, oldState) {
var that = this;
var httpRequest = new XMLHttpRequest();
var httpRequestURL = "https://mysupersweetdomain.com/my-route";
httpRequest.open("POST", httpRequestURL, true);
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Get Response Data
var data = this.responseText;
data = JSON.parse(data);
// Update State With Fresh Financial Data HERE
var newState = oldState;
newState.foo = data.foo;
newState.bar = data.bar;
newState.baz = data.baz;
that.setState(newState); // update state with fresh financial data
}
};
var formData = new FormData();
formData.append("abc", paramOne);
formData.append("xyz", paramTwo);
httpRequest.send(formData);
}
view raw thatEqualsThis.js hosted with ❤ by GitHub
 

ReactJS: Button Disappears onClick, Doesn’t Reappear Until User Clicks Somewhere Else on Screen

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

Woah there distraught ReactJS developer, fret not! If you have buttons in your ReactJS app disappearing after onClick events are fired, all you need to do is remove whatever 3rd party styling you are currently applying to your buttons, and then see what happens. In my case, the default RatchetCSS styling for “btn” classes was causing this wonky behavior in my app. However, all I had to do to fix things was remove this 3rd party class from my button, and everything started working as expected once again. Last, simply add your own styling back to your buttons and you should be back in business! (Also, if you happen to be using Bootstrap in your project and run into this problem, try using react-bootstrap instead.)

 

Integrating ReactJS into an Apache Cordova Project

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

Hello There Dear Internet Friend,

This post is more of a sticky note / bookmark for my own personal reference, however, maybe it will be of some use to fellow Apache Cordova and budding ReactJS developers. If you happen to be getting into hybrid app development using Apache Cordova and are interested in integrating ReactJS into your project, one problem you may encounter is that the tooling for both ReactJS and Cordova are a bit complicated. For example, when creating a new ReactJS project you typically use the command line program create-react-app to bootstrap a new project. Likewise, Cordova uses its own command line program for bootstrapping projects. Unfortunately, the starter project skeletons that these tools create aren’t exactly compatible. Think about how complicated this really is:

  • First you need to transpile your ReactJS project into JavaScript that the browser can actually understand.
  • Then you need to compile your web-based app into a native app using Cordova.

Essentially, you have to compile everything, then compile it all again! Double Compilation

Which brings us to this blog post! I’ve found several resources out there on the web that look like good places to start if you are having trouble with this complicated toolset and build process:

Resources on ReactJS + Apache Cordova

  1. PhoneGap and React.js | PhoneGap Day US 2016
  2. cordova-create-react-app by John Zhou

PhoneGap & ReactJS @ PhoneGap Day US 2016

cordova-create-react-app Tutorial by John Zhou

# Cordova Create React App Tutorial
I was dissatisfied with tutorials that didn't meet my needs, boilerplate projects with incompatible dependencies, and yeoman generators with errors so I decided to make a tutorial to help others set up their initial project. Also if you're migrating an existing web app to Cordova, this will provide insight into what you need to get that to work.
Note that I'm running this tutorial with Cordova 8 but it should work with other versions.
## Installation
Install the Create React App CLI.
`npm install -g create-react-app`
Install the Cordova CLI.
`npm install -g cordova`
Create the project.
`create-react-app tutorial`
Because we will be editing the Webpack configuration, go to your Create React App project directory and run:
`yarn run eject`
Go to your config/paths.js file and change
`appBuild: resolveApp('build')` to `appBuild: resolveApp('www')`
Because your files will be served from `file://` add this line to your package.json (https://github.com/facebookincubator/create-react-app/issues/1094):
`"homepage": "./"`
This is specific to create-react-app. In other projects you would need to ensure your paths are not prepended with a /.
Now we will need some files from a Cordova project.
`cordova create tutorial com.example.tutorial Tutorial`
Next copy the config.xml from your Cordova project to your Create React App project. The other files and directories in the Cordova project are not currently used in this tutorial but take note of them because you may make use of them as your project develops. For example, the `res` directory would be where you would place icons and splash screens.
Next modify your index.js so it looks like:
```
const startApp = () => {
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
};
if(window.cordova) {
document.addEventListener('deviceready', startApp, false);
} else {
startApp();
}
```
And add `<script type="text/javascript" src="cordova.js"></script>` to index.html. You may also want to add
```
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
```
Now we can build our output to the www directory.
`yarn run build`
The rest of these instructions have files and changes that are not in the current repository due to the nature of the dependencies that have to be brought down. Also I didn't want to tie the tutorial down with specific versions of Android and iOS.
To target platforms:
`cordova platform add ios`
`cordova platform add android`
You need to install SDKs for each platform that you wish to target. Read this to check what requirements need to be satisfied: https://cordova.apache.org/docs/en/latest/guide/cli/index.html#install-pre-requisites-for-building
Generally you will probably have to install Android Studio, XCode, SDKs, emulators, build systems, etc.
To test the app run:
`cordova emulate android`
`cordova emulate ios`
To test on a connected devie run:
`cordova run android`
`cordova run ios`
## Recommended Plugins
Often what you will find is that a plugin is no longer being maintained. In that scenario your options are either to find a fork that resolves the issues you are encountering or, as a last ditch effort, attempt to fix it yourself.
### Firebase OAuth Authentication
To authenticate using OAuth Providers follow these instructions: https://firebase.google.com/docs/auth/web/cordova
Because the cordova-universal-links-plugin is outdated you should instead install this fork:
```
cordova plugin add https://github.com/walteram/cordova-universal-links-plugin.git --save
```
### Firebase Analytics and Push Notifications
Due to various issues that haven't beeen resolved in the latest npm package of cordova-plugin-firebase I recommend getting the version of the plugin directly from git
```
cordova plugin add https://github.com/arnesson/cordova-plugin-firebase.git --save
```
## iOS Deployment
First, sign up for a paid Apple Developer Account. In Xcode, open your project from `/platforms/ios` and go to your Preferences > Accounts. Add the Apple ID that was used for the developer account. Select your Agent Role and click on `Manage Certificates..` and click on the `+` icon to generate a signing certificate.
Next, go to `https://developer.apple.com/account/ios/profile` and add a new provisioning profile. Select your development or distribution option and on the next page fill your App ID Description (for example, My Cordova App) and your bundle ID that can be found in config.xml.
Next, in Xcode go to your project navigator and select your project. In a drop down list make sure your project is selected as a target. Then, under Signing, select your Team and generate your signing certificate.
To prepare for distribution on the Apple App Store, you need to create an archive. In Xcode make sure the app is properly provisioned and signed for distribution. Next run `yarn build` followed by `cordova prepare` to copy any assets and plugins. Then in Xcode, ensure the version and build numbers are properly set and choose a generic device target from the Scheme toolbar menu. Then choose Product > Archive. There is an issue uploading to the App Store from the Archives window. Instead export the archive and upload it via Application Loader. After uploading the build to iTunes Connect, if the build is still in the "Processing" phase after an hour, attempt to upload another build because more than likely there's probably an issue with Apple's servers.
## Android Deployment
First, sign up for a Google Play Developer account. Next, run `yarn build` followed by `cordova build android --release` which will result in an apk that needs to be signed. Then run:
```
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore android.keystore app-release-unsigned.apk alias-name
```
where `android.keystore` is the location of the keystore and `alias-name` is the alias for your key. Make sure you have Android Studio installed because it will also come with the zipalign tool. For Mac OS you can find it in `~/Library/Android/sdk/build-tools/{version}/zipalign`. Then run:
```
~/Library/Android/sdk/build-tools/{version}/zipalign -v 4 app-release-unsigned.apk release.apk
```
followed by uploading the build to the Google Play Console.

UPDATE (11/3/2019): I was able to successfully run my ReactJS web application as a hybrid mobile application using Apache Cordova. How I did it was:

  1. Used “$ npm run build” to produce a production build of my ReactJS app for distribution, and then…
  2. Instead of deploying the build to a web server, I copied the contents of my ReactJS app’s build directory over to my Cordova app’s “www” directory (the “www” directory needs to be empty).

Two other crucial steps were adding a script tag importing cordova.js in the ReactJS app’s index.html file, and to add a "homepage": "./" key value pair in the package.json file of the ReactJS project. I’ll try to write/film a more detailed follow up blog or vlog post about this soon. But for now, here is the referenced I used to figure out how to do all of this! (I did not follow it exactly): Creating Structure for Create react app and Cordova

 

Trouble Getting the Auth0 Quickstart Tutorial for PHP to Work? Does Your Application Keep Redirecting to http://localhost:3000/?code=

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

Having trouble getting the official Auth0 quickstart tutorial for PHP to work? Keep getting redirected to http://localhost:3000/? Okay so here’s what may be going on:

First, this tutorial was meant to be run on a local development server, not in a production environment, thus all the localhost business. To fix this I had to do a few things. First, make sure you allow both your actual web facing callback url and localhost under Allowed Callback URLs on the Settings Page.

Second, you may need to go into your PHP scripts and set the $redirect_uri variable equal to a string containing your actual live web facing callback url, instead of the default getenv(‘AUTH0_CALLBACK_URL’). For example, see the picture below. I’ve commented out getenv(‘AUTH0_CALL_BACK_URL’) and hard-coded my actual callback url. You could also change the environment variable from the command line, but this would have been a lot of trouble for me as I’m using shared hosting to host multiple domains on one of my servers using Plesk. So try and simply hard code your callback url if you are having trouble, or change the environment variable from the command line if you want do things the correct and secure way.

Now just make sure to save your changes on the Auth0 Settings Page before you attempt to log in again, and that’s it!

 

Hello, World with ReactJS in 8 Easy Steps: From Local Windows Development Machine to Live Production Server

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

Hello There Dear Internet Friend,

This post is mainly for my own personal reference, but maybe it might be of some help to someone else out there on the ole interwebs as well. So let’s begin. 8 easy steps to creating a ReactJS app on Windows 10 (assumes you have already installed node.js) =>

  1. Fire up the command prompt and navigate to your Desktop directory
    $ cd Desktop
  2. Use create-react-app to generate a new React project
    $ npx create-create-app hello-react
  3. Navigate to your new project directory
    $ cd hello-react
  4. User npm to start your development server
    $ npm start
  5. Edit src/App.js and save to reload changes
  6. CTRL-Break and enter ‘y’ to ‘terminate batch job’ if you’d like to stop the development server
  7. Build your app for production using npm
    $ npm run build
  8. Last, upload the file from the build folder to your server with ftp and FileZilla, or using a more modern method if you so choose, when your ready for your app to go live on the world wide web. Happy hacking!