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 blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

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);
}
 

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

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

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 blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

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 blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

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!
 

How to Reload, Refresh, Update, Webpack, Transpile, or `Whatever You Want to Call it` a React App on Glitch.com

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!

Tonight I discovered this really cool quickstart tutorial on ReactJS from the team at Glitch.com where you can actually start programming in ReactJS in your browser using the Glitch.com web-based coding environment without having to use create-react-app or webpack to build your app. They handle all of the hosting and tooling for you. Pretty neat huh?

The only problem is hot reloading doesn’t always work. But after a little fiddling around I figured out a work around to get Glitch to sometimes hot reload everything when necessary: Simply go in and add a comment to the server.js file to trick glitch into hot reloading everything =>

// glitch reload!

If that doesn’t work, which it may not as I’ve found. You may just want to try using REPL.it instead to do your ReactJS coding practice in the browser using a web based coding environment. After playing around with REPL.it’s competing ReactJS browser based coding environment, I think it is probably a little bit better, albeit somewhat slower.

So there you have it. Maybe the best way to get started with React and Glitch is to watch their excellent 5 part video tutorial, but actually do your coding on REPL.it instead.

 

My Job Application to Plaid Inc.

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Submitted a really interesting application to Plaid Inc. tonight… through their API! Pretty interesting huh? Originally I submitted an application via the startup social network AngelList, but happened to discover their “Apply by API” option while checking out their careers page. Wish me luck!

My Application & Server Response from the Plaid API:

# REFERENCE: GET and POST requests using Python
# https://www.geeksforgeeks.org/get-post-requests-using-python/
# REFERENCE: Post JSON using Python Requests
# https://bit.ly/2w6YHGa
import requests
import json
url = "https://contact.plaid.com/jobs"
data = {
'name': 'Christopher Pedersen',
'email': 'chris@topherpedersen.com',
'resume': 'https://bit.ly/ChristopherPedersensResume',
'github': 'https://www.linkedin.com/in/christopher-pedersen-a54a87b6/',
'twitter': '@topherPedersen',
'website': 'https://topherpedersen.blog',
'location': "Dallas, TX",
'favorite candy': 'Butterfinger',
'superpower': 'Wingsuit Pilot'
}
data = json.dumps(data)
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
http_post_request = requests.post(url=url, data=data, headers=headers)
server_response = http_post_request.text
print(server_response)
 

PhaserJS Starter Template

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Phaser 3 Starter Template for use with my students @ theCoderSchool =>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.19.0/phaser.js"></script>
<script src="game.js"></script>
</body>
</html>
view raw phaser.html hosted with ❤ by GitHub
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 200 }
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var game = new Phaser.Game(config);
function preload () {
}
function create () {
}
function update() {
}
view raw game.js hosted with ❤ by GitHub
 

CordovaError: Promise rejected with non-error: ‘xcode-select: error: tool \’xcodebuild\’ requires Xcode, but active developer directory \’/Library/Developer/CommandLineTools\’ is a command line tools instance\n’

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Okay, so it looks like you’re having some trouble trying to run your Apache Cordova app on your iPhone. No worries! This blog post should get you pointed in the right direction.

First, if you happen to be receiving this CordovaError regarding xcode-select try installing this one dependency before attempting to run the app again on your device:

$ npm install -g ios-deploy

This is what the Official Cordova documentation suggests doing. However, this actually didn’t work for me for whatever reason. Luckily, I was able to install ios-deploy using brew instead, so maybe you should try that:

$ brew install ios-deploy

Now even though you should have all of the required dependencies installed (assuming your ran a traditional hello, world with swift and Xcode before installing Cordova), you may still find that you are running into the same error. The next step towards my eventual solution was running the following command to fix xcode-select:

$ sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

We’re getting closer. But I happened to next encounter an error message that read something like…

error: Signing for “HelloCordova” requires a development team. Select a development team in the Signing & Capabilities editor. (in target ‘HelloCordova’ from project ‘HelloCordova’)

The last step you need to take is to log in to developer.apple.com to figure out your developmentTeam identifier so you can set the developmentTeam flag when you go to run the app. This should fix the above error message. The developmentTeam identifier is located next to your name when you log in to developer.apple.com up in the top right hand corner of the website.

Last, run the app while remembering to set the necessary flags:

$ cordova run ios --device --developmentTeam="XX34TU9917" --automaticProvisioning=true

P.S. I made up the XX34TU9917 developmentTeam, so make sure you use your actual developmentTeam identifier found at developer.apple.com.