Share Tweet Reccomend

To Do: Create Your First React Application – Part I

React is a JavaScript library that is primarily responsible for handling the “view” component of a JavaScript single-page application. As it describes itself of the React homepage…

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.

React’s focus, first and foremost, has to do with rendering dynamic UIs in a manner that is visually appealing to the user. It is flexible enough that it can be used in a diversity of capacities and contexts. We have looked at React in previous entries. In what follows we will look at creating an introductory application using React and React related tools and libraries. One of the more ubiquitous tutorial applications that developers build when learning a new language or framework is the TO DO (To do) app. In terms of prevalence, it is probably second only to the “Hello, World” app which has been around since the dawn of programming. But the “To Do” application is popular because it covers a lot of the basics of how a language or framework handles a number of things. There must be a way to add a new “to do” so handling user input is involved. The same is true for displaying data, editing and saving data, and changing display state when data updates. All of these things are going to be important implementations in any application.

In what follows we will create the iconic “To Do” application in React and discuss some of the inner workings as we go along. We will take a deeper look into React components and how we can add some dynamic interactivity to our React applications in response to user actions — things like clicks and entering text in a text box — and updating our views accordingly.

JSX Compilation with Babel & Browserify

As we will see, React has its own programming language called JSX. It has been described as sort of like a mixture of JavaScript and XML and it is React’s own special easy-to-read abstracted syntax. JSX is not required to create React applications and you can write your React components in native JavaScript if you prefer. Because browsers do not natively understand JSX in order for your react application to run JSX needs get converted to native JavaScript.

The React website suggests that you utilize tools like Babel and/or Browserify (both of which run on Node.js). Babel is what is known as a transpiler. It mostly functions as a tool that takes code written in ECMAScript 6 (ES6) and converts it to ES5. As of 2015 this is still necessary because support for ES6 across all browsers is not widespread yet. Until support for ES6 is implemented across all browsers, tools like Babel will still be needed. Although many people think of Babel primarily as an ES6 to ES5 transpiler, Babel also comes with JSX support as well. You can merely run the Babel transpiler on your JSX files and they will be converted to native JavaScript that will be recognized by any browser circa 2015.

Browserify allows for Node.js style module loading in your client-side JavaScript. Like with Node, it allows you to import code in certain JavaScript files into other JavaScript files for better organization of your code.

Task Runners / Module Bundlers

For our sample code, we will be using task runners to handle our JSX conversion to native JavaScript. You may have heard of task runners like Grunt or Gulp, or module bundlers like webpack. We will be using webpack because it has, at least for the time being, become the utility of choice among the React community. If you are not entirely familiar with JavaScript task runners it would definitely be worthwhile to read the webpack documentation (or watch a few videos) on what it is and why you would want to use it. The more recent versions of React essentially require you to set up your tools before you work with JSX in React. In previous versions of React there was an easy extra <script> tag that you could add in your HTML to make it easy to implement JSX. However this has since been deprecated. If this seems daunting and you are already feeling overwhelmed, not to worry! We will walk through how to set everything up before we dive into React coding.

Setting Up

To start we need to set up our package.json and webpack.config.js files so that we can set up our tools to do JSXcompilation to native JavaScript. Create a new directory and then create a package.json file and add the following…

{
    "name": "React",
    "version": "0.0.1",
    "description": "A React application...",
    "license": "MIT",
    "repository": {
        "type": "",
        "url": ""
    },
    "homepage": "https://9bitstudios.com",
    "scripts": {
        "start": "webpack-dev-server --progress"
    },    
    "dependencies": {
        "react": "15.3.0"
    },
    "devDependencies": {
        "webpack": "1.13.1",
        "webpack-dev-server": "1.14.1",
        "babel-core": "6.13.0",
        "babel-loader": "6.2.4",
        "babel-preset-es2015": "6.13.0",
        "babel-preset-react": "6.11.1"
    }
}

Next, in this same directory, create a webpack.config.js file and add the following…

var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: __dirname + "/src/App.js",
    output: {
        path: __dirname + "/dist",
        filename: "App.js"
    },
    watch: true,
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',
                query:{
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    devServer: {
        colors: true,
        inline: true
    },     
    plugins:[
        new webpack.optimize.UglifyJsPlugin(),
    ]
};

After this, let’s open a command prompt and run the following…

$ npm install

to install all of our modules that we will need for compiling ES6 and JSX. And that is all there is to it. Now that we have our tools installed and configured, we can dive into writing our application.

Writing a “To Do” Application

So let’s get started creating our “To Do” app. We will start out by creating our index.html file…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div id="content"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
    <script type="text/javascript" src="dist/App.js"></script>      
    
</body>
</html>

As we can see, we are going to include App.js, which will be a file that we generate in our task runner. Note too we are creating a

with the id of “content.”

Next, create a folder called “src” and create a file called App.js in this folder. For this tutorial we are going to be breaking our components up into different modules so in our App.js file all we need to add for now is the following.

import {react} from 'react';

In the same directory as your App.js file, next create a file called “Todo.js”. In this file, we are going to need to create a React component/class that will represent each individual “to do.” Add the following code to this file…

import {react} from 'react';

class Todo extends React.Component {
    
    render() {
        return(<div>I am a to do</div>)  
    }
};

Pretty straightforward. This should look familiar as it is similar to our other earlier examples.

Now what we’re going to do is import this module into our App.js file. How do we do this? In our App.js file we just need to add the following…

import {react} from 'react';
import {Todo} from './Todo';

This will tell our code to import the “Todo” module from the “Todo” file relative to where “App.js” is located. With module loading in ES6 you can omit the “.js” from the file when you are importing modules.

So we are definitely well on our way but if we were to run this code as it is right now we would get an error. Why is this? Well, because we are importing a module from our “Todo.js” file we need to specify what this file exports. To do this we need to add the “export” keyword in front of what we want to make available from the “Todo.js” file. Thus, we need to change our code in our “Todo.js” file to the following…

import {react} from 'react';

export class Todo extends React.Component {
    
    render() {
        return(<div>I am a to do</div>) 
    }
};

Notice how we have added the “export” keyword in front of our class. Now there is something that can be imported from the “Todo.js” file. We will get into more complex combinations of what various files can export and import later on, but for now this simple example shows the basic setup of how it is done.

Now in our App.js file add the “render” method so we can confirm that everything is working…

 import {react} from 'react';
import {Todo} from './Todo';

ReactDOM.render(<Todo />, document.getElementById('content'));

Let’s build our App.js file by running “webpack” by opening up a terminal window typing the following…

$ webpack

Doing the above will build the App.js file and place it in our “dist” folder. Now if we open up another terminal window and run our server with…

$ npm start

and we go to https://localhost:8080 in our browser, if all has gone well we should be able to see the text “I am a to do.”

Component Composition

For our application we will be rendering a list of “to do” items inside of our “to do” list. Thus, we will also need to create a component that represents our “to do” list. So create a “TodoList.js” file in the same directory as the others and add the following code…

import {react} from 'react';
import {Todo} from './Todo';

export class TodoList extends React.Component {
    
    render() {
        return(<div>To do list here...</div>)  
    }
};

“TodoList” is the component that will serve as our “root” container component for our React application. It is just returning some placeholder text for now, but we will be adding more complexity to it very soon. Because the “TodoList” top-level component for this particular application, it is this one that will be the one that we want to render in our App.js file (not the individual “Todo” components). So change the code in our App.js file to the following…

import {react} from 'react';
import {TodoList} from './TodoList';

ReactDOM.render(<TodoList />, document.getElementById('content'));

Notice now how we are now rendering the “TodoList” component now and not the “Todo” components.

Read More »

, , , ,
Share Tweet Reccomend

Submit Apache Cordova Applications for iOS and Android to the Apple App Store & Google Play

In the past, we have looked at setting up Apache Cordova mobile applications for iOS and Android with HTML5, JavaScript and how to develop for this versatile platform. In what follows we will look at how to submit your application to the app stores of the respective platforms once you have finished developing your application.

As we looked at before, you will need a computer with the SDKs of the platform(s) you want to release on. If you want to release for Android devices, you will need to grab the Android SDK. I actually recommend you install Android Studio as this will download everything you need for this and future releases. If you want to release for iOS devices, you will of course need a Mac computer with Xcode installed. Unfortunately, you cannot develop iOS applications without a Mac. So if you want to build and release for iOS you will have to find some way to get access to one.

You will also need to sign up for developer accounts for the platforms you want to release on. These developer accounts do cost money. For Google Play (Android) there is a one time developer fee of $25. For an iOS developer account the fee is $99/per year.

Once you have signed up for your developer accounts, we can build our applications for release on the iOS and Android platforms.

Submitting to Your Cordova App for iOS to the Apple App Store


Once you are satisfied with how your app functions on all of the devices that you want your application to run on, you can start the process of preparing your project for submitting your app to the Apple App Store.

To submit your Apache Cordova application for sale (or free download) on the App Store you will need to go through the normal process that all apps must go through before they are submitted to the store. Building an app for release on iOS is a fairly straightforward process. You need to compile the release file by running the following command in the root of your Cordova project…

$ cordova build --release ios

This will build your application for release. There will be a generated Xcode project in the platforms/ios directory

Next, you’ll need go to https://developer.apple.com and click on “member center.” Sign in with your developer account if you have not already.

Creating an iOS Distribution Certificate

Click on “Certificates Identifiers and Profiles” and then on the next screen click on “Certificates.”

Click on the “+” button on the certificates page and scroll down in the production section and choose the “App Store and Ad Hoc” option and click “Continue”

iOS

We will want to create a new certificate so we will need to open up Keychain Access. The easiest way to do this is in your Mac click on the search bar in the top right and search for “Keychain Access” and open this application, Click on Keychain Access in the menu in the top left, and in the dropdown hover over “Certificate Assistant” and choose “Request a Certificate From a Certificate Authority”

iOS

This will open up a modal which you can then fill out the e-mail address with your developer account e-mail and then a common name which can usually just be the same of your organization. After you have filled these out choose the “Save to disk” option and save the certificate to wherever you want on your computer.

iOS

Read More »

, , , , , , ,
Share Tweet Reccomend

Develop Apache Cordova Applications with HTML5 & JavaScript

In a prior discussion we looked at how to set up a project so that we could develop an Apache Cordova application using HTML5 and JavaScript. In that section we mostly covered how to set up, build, and run the project — which consisted of the same application in the www folder that Apache Crodova bootstraps when you create a new project. In what follows we will look at the approach for actually writing own code for our app and will look at how an app in Apache Cordova gets initialized. We will also look at how we can extend the Apache Cordova platform by using plugins to give ourselves additional features and functionality that will make for an all around better user-experience (UX) for the users of our app.

Now that we have our project set up and all our platforms added all that we have left to do now is create our application by creating what basically amounts to a website that runs HTML and JavaScript in the “www” folder. How should one develop for Apache Cordova? Personally, I would delete all of the boilerplate files and folders and start from scratch. That is what we will do here. Just take a quick note of how things are referenced in the index.html file and do the same for your own files.

In doing this, I have modified the index.html file in the “www” folder to the following…

<!DOCTYPE html>
<html>
    <head>
        <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 *">
        <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="stylesheet" type="text/css" href="css/index.css">
        <title>Cordova Application</title>
    </head>
    <body>
        
        <div id="main">Initializing...</div>
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

Note: Do not worry about that “cordova.js” reference or the fact that this file is nowhere to be found in our “www” folder. Apache Cordova will utilize this in the proper context when the app runs (so leave it in there).

So as far as the index.html goes, there is nothing too fancy. I have a css file (index.css) and a js file (index.js). That is all you need to get started.

Next, let’s look at our JavaScript in the index.js file. There is really only one thing you need to make note of when you develop Apache Cordova applications in JavaScript. There is a special event that Apache Cordova uses to tell the platform that the everything is loaded and the device you are using is ready to start running JavaScript in your Cordova application. This is what is known as the “deviceready” event. It only fires when you are running an app within a Cordova context (i.e. on a device or an emulator of a device). In a lean version of JavaScript for a cordova application would look like the following (in index.js)…

var app = {
    init: function() {
        document.addEventListener('deviceready', this.main, false);
    },
    main: function() {
        document.getElementById('main').innerText = 'App is ready...'
    }
};

app.init();

Here we are calling the “init” function which will add a listener for the “deviceready” event. When this event fires the “main” function will run, which in this case just changes the inner text of a div element So if we run this using

$ cordova emulate android

or

$ cordova emulate ios

from the root of our project we will see our device boot up, our app launch, and if all goes well we will see the text “App is ready…” so we know that our event is firing.

Read More »

, , , , , , , , , , ,
Share Tweet Reccomend

Create Mobile Applications for iOS and Android with HTML5, JavaScript, and Apache Cordova

Obviously at the time of this writing in the 2nd decade of the 21st century, you are no doubt well acquainted with the immense proliferation and impact that mobile apps have had in and on our world. It was not long ago that we were all sitting at our computers at our desks for the large majority of the time we spent in our various avenues of technological communications over the Internet — complete with our with our giant monitors, whirring computer fans, buzzing drives, and the garbled noise of dial-up modems. Now, mobile phones and tablets probably make up as much, if not more, of our time spent working, playing, and communicating online. Everyone has a ~$100 to $600 smartphone (i.e. computer) in their pocket. And with this rise of mobile, apps found on the popular stores — like Apple’s iOS App Store, Google Play (Android), Amazon and a host of others — have completely transformed the way that we do anything and everything because well, there is an app for anything and everything. Every single facet of life probably has an app to manage some aspect of it. Need to remember to breathe? There is an app for that! Yeah, that is a joke (probably)… but there are plenty of “real” apps out there (e.g. iBeer) that are just as pointless. Fun and goofy, yes, but pointless. And they all post their pointlessness to Facebook and/or Twitter.

Whether you want to develop an app to manage some minute aspect of life or just create a fun game, or whatever else, you can download the SDK for the platform(s) that you want to release your app on, do some tutorials, and start building. That’s all well and good, but if you want to port your application to another platform (e.g. release an iOS app also for Android), you will essentially have to try rebuild the same app using the languages in tools of a different platform. For example, iOS apps for iPhone and iPad have traditionally been developed on a Mac in the Xcode IDE using the Objective-C programming language (though Apple has recently released a new language called Swift that can also be used to build iOS apps). Android apps, by contrast are built using Java and Eclipse or the more recently released Android Studio. Native Windows Phone apps are built using C# and XAML in Visual Studio. Other platforms have their own setups. If you want to take this approach you definitely can, but it should be fairly apparent that developing and maintaining a number of different codebases for multiple platforms quickly adds up to a lot of time, effort, and often money as the sizes and complexity of your apps increase.

At the same time as the rise of mobile in the past decade, something else has occurred: the rise of HTML5 and JavaScript web applications. Beginning at around 2009 – 2010 one of the more noticeable developments was the rise of websites and web applications making use of more open technologies such as HTML5 and JavaScript to bring interactivity and 2-way communication between clients (usually browsers) and servers. With Flash on the way out due its proprietary nature, resource hogging, security issues, poor SEO — along with its being snubbed by Apple for support on iPhones and iPads for basically all these reasons — meant that something had to fill the void. HTML5 and JavaScript moved into this space and developers started turning to it for creating interactive “app-like” experiences.

Wouldn’t it be awesome if there were a way to write a single application in HTML and JavaScript with a single codebase and have a way to port this application to all of the different mobile platforms? I am so glad you asked.

Apache Cordova — also commonly known as “PhoneGap” (the only difference between the two is propriety) — allows us combine combine these open technologies together with the SDKs of the various mobile application platforms to make native mobile applications using technologies such as HTML and JavaScript. You can basically create a small static HTML and JavaScript website or web application and this code will be imported into native iOS, Android, Windows Phone projects and configured specifically for the respective platforms. Thus, you *do* still have to have the SDK of the platform installed to build, run, and release the apps. So to create an iOS app you will still need a Mac and Xcode. To create Android apps you will need to install the Android SDK (which comes with the Android Studio IDE). If you don’t want to mess around with Android Studio, you can just try downloading the old standalone SDK tools here and updating from there. But the important aspect of using Cordova is that the HTML and JavaScript that each project will pull in and build will be the same across all platforms. Want to release an update with some slick new features or fix some bugs that have been reported by your users? You need only change your code in your HTML and JavaScript. You don’t have to try and rewrite the same code and/or functionality in a different language on each platform. From there all you need to do is run a few simple commands from the command lines and your HTML and JavaScript will get built and converted into an application that can run on the platform(s) you are targeting.

In what follows we will explore what it looks like to use Cordova to create a mobile application in HTML and JavaScript that can run on a number of different platform. For our examples, we will build our app for iOS and Android, but the process is essentially the same for building for other platforms (e.g. Microsoft Windows Phone, Amazon Kindle Fire). You would just need to download the SDKs for those platforms if you wanted to run your app on those types of devices as well.

Read More »

, , , , , , , , , , , ,
Share Tweet Reccomend

Debugging Node.js Applications with Node Inspector

Debugging is an important part any sort of application development. If you have errors or unexpected results occurring in your code you need to be able to step through your code and find where things are going awry. Thus it is very important that you are able to see what is happening at specific times when your code is executing. There are some IDEs (integrated development environments like Visual Studio or Eclipse) where debugging for the native application language like C# or Java is all built right into the tools and you don’t have to do anything to set it up. At the time of this writing in the later part of the year 2015, there are a few IDEs such as WebStorm and Komodo IDE that natively support Node.js debugging but this is often the exception rather than the rule (at present). Node.js, being a younger and relatively more immature platform often does not have debugging for it natively implemented in most IDEs yet. Fortunately, there are often plugins available that will enable Node.js debugging within the IDE. Node.js tools for Visual Studio 2012 and 2013 is one example. Nodeclipse is a plugin that will enable Node.js debugging capabilities in Eclipse.

Because there are so many different development environments and workflows that different developers have different preferences for we won’t look at debugging Node.js applications in a specific IDE. But we will look at a specific debugger called Node Inspector. There are other Node.js debuggers out there and if you want to use another debugger that is fine. You would just have to look at the docs for that particular debugger. It should be noted that Node Inspector works in Chrome and Opera only. You have to re-open the inspector page in one of those browsers if another browser is your default web browser (e.g. Safari or Internet Explorer). This is another indicator that shows widespread support for many things in and within Node.js is not entirely quite there just yet. So much of the Node.js module ecosystem is community driven, which has very noticeable pros and cons. The upside to this it is that there are a lot of awesome components of functionality that you can leverage via installation with a simple $ npm install of a module. The downside of this environment is that support and/or consistency for bug fixes and releases can vary quite a bit depending on who’s module(s) you are using. Just as a personal opinion, I find that on the whole the positives outweigh the negatives when it comes to open source software. I would much rather take this scenario over, say, a behemoth corporation owning and managing all of the releases that might seem more “professional” in its support and maintenance (as opposed to hobby/side-project code). But developing in and for open source applications is definitely far from perfect.

But all that aside, let’s get back to fun with Node.js debugging. Node Inspector works almost exactly as the Google Chrome Developer Tools. If you are not entirely familiar with Google Chrome’s developer tools read the DevTools overview to get started. Dev Tools can be used to set breakpoints in your application that halt the execution of the code when a certain statement (or statements) are reached. From there you can examine the state of particular objects to see what values they contain at that point in time. You can then step through your code moving from one statement to the next to see how the values change. If this all seems a little bit confusing at this point, not to worry. We will revisit this a bit later when we actually take on the task of debugging our application. But first we need to install the stuff we need to get debugging up and going.

Installing Node Inspector

To install Node inspector we will use the npm utility to install Node Inspector from npm.

$ sudo npm install -g node-inspector

Note: Windows 8.1 Users: At the time of this writing in the later part of 2015 for Windows 8.1 I had to omit installing an optional dependency which apparently breaks the install using npm. The way that you do this is by setting the –no-optional flag…

$ npm install -g node-inspector --no-optional

That should get it working for you. To check that it installed correctly you can always run

$ node-debug --version

which should output the version number for you without any error messages.

Sample Application

For our application we will use a sample API that I often utilize for demonstrating Node.js applications that uses Express.js as an application framework. If you are not familiar with Express there is an introduction to Express here. If you need a quick refresher on Node.js by any chance you can read A Node.js Primer. For a more in-depth look at Express.js, there is also an ongoing series entitled Creating an MVC Express.js Application.

Read More »

, , ,