Share Tweet Reccomend

To Do: Create Your First React Application – Part II

Previously, we looked at getting set up creating a React “to do” application by installing our Node.js driven build tools and laying out some introductory components of code. In what follows we will continue on where we left off.

Adding “To Do” Items & Handling User Input

So far we have just looked how to display our components. Rendering data out to our page is all well and good, but to make our application truly dynamic we are going to need to implement a way to add and remove items to and from our list as well as edit them should we need to make any changes to any of the properties. So let’s update the code in TodoList.js to the following…

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

export class TodoList extends React.Component {
    
    constructor(){
        super(...arguments);
        this.state = {
            todos: this.props.data,
            addTodoTitle: '',
            addTodoSummary: ''
        }
    }
    
    addTodoTitleChange(e){
        this.setState({
            addTodoTitle: e.target.value
        });        
    }
    
    addTodoSummaryChange(e){
        this.setState({
            addTodoSummary: e.target.value
        });           
    }    
        
    addTodo(){
        this.state.todos.push({
            id: this.state.todos[this.state.todos.length - 1].id + 1,
            title: this.state.addTodoTitle,
            summary: this.state.addTodoSummary,
            done: false
        });

        this.setState({
            todos: this.state.todos,
            addTodoTitle: '',
            addTodoSummary: ''
        });        
    }
    
    render() {
        
        var items = this.props.data.map((item, index) => {
            return (
                <Todo key={item.id} title={item.title} summary={item.summary} completed={item.done} />
            );        
        });
        
        return(
            <div>
                <ul>{items}</ul>
                
                <h3>Add New Item:</h3>
                <label>Title</label> <input type="text" value={this.state.addTodoTitle} onChange={() => this.addTodoTitleChange()} />
                <label>Description</label> <textarea value={this.state.addTodoSummary} onChange={() => this.addTodoSummaryChange()}></textarea>
                <button onClick={() => this.addTodo()}>Add New Item</button>
            </div>
        )
    }
};

So let’s discuss what is going on here. We have added 2 new values to our initial state object and we have created a form that will allow us to add a new “to do” item to our list. When we enter text into these fields the functions to update the state will run and we will update these values with setState by getting the current value of the form element we are editing off of the event that is passed into the function (e.target.value). Once we have filled out the form with the title and summary of the new item that we want, we can click the “Add New Item” button which, as we can see from our “onClick” handler, will run the “addTodo” function. If we look at this function we can see the code that we will need to add a new item to our list. Recall that we have to give each individual item an id and no two items can have the same id. So to generate a new id we will look at what the id value of the last item in our array is and just add 1 to that. That is an easy way to ensure that the new items that we add are always unique. We get the title and the summary from this.state which we have been setting in our text input handler functions. Lastly, we just set the initial value of the “done” flag to false since adding a new to do to the list is presumably not done yet. All of this data is passed into the common JavaScript Array object’s “push” method. We then update the state of our “todos” and then clear out the input text box and textarea in our form to get them ready to receive another value.

So build your code with $ webpack (or whatever task runner you are using) and try it out. You can see how we can now add new items to our list! Pretty slick!

Improving Our Code

Our example above works but you may have noticed something problematic with our implementation. We have individual handler functions for the two text elements in our “Add New Item” form. We also have separate properties that we use for setState. This is fine for this simple example, but what if we had a component with many different properties and values with many different fields that needed to be filled out? If we were to take the same approach as our example above, we would have to create an individual function for each and every property. Not too efficient!

Read More »

, , ,
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

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

Introduction to React

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 mentioned earlier that there are a number of different MVW/MV* JavaScript frameworks and all of them have different implementations in how they handle the various aspects of a JavaScript application. Naturally they all have different ways that they handle rendering visual representations of the data that the application is handling. Backbone.js natively uses Underscore.js templates, Ember users Handlebars.js, and Knockout.js and Angular have their own syntax. With a little bit of work you can swap view engines within these frameworks if you so choose. And it would be here where we could incorporate React to handle the view rendering portion of an application. But, as mentioned above, React is not dependent on any JavaScript framework being in place. It can be used as a standalone aspect of an application almost entirely independent from any other library or environment.

So why go to the trouble to incorporate React? Why not just use a framework’s native rendering engine (if you are using a framework). If you are not using a framework, why not just use something like jQuery to handle your view layer? Again, looking at the React homepage, the following description is provided…

React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.

As it turns out there are a number of different positive aspects in terms of performance, scalability, and simplicity that React can provide to application development as it progresses along in both size and complexity. We will explore these in detail as we go forward. As many have noticed, React is a little bit unorthodox from “traditional” JavaScript application development (if there were such a thing) and it can take a little bit of working with it and a little bit of trial and error before many of the benefits of it are fully realized. Indeed, many developers admit that they did not quite “get it” at first and some have even described a substantial initial aversion to some of its implementations. So if you experience this on any level, you are definitely not alone and I would merely invite you to “stick with it” through some of the initial tutorials before you run for the hills screaming in terror. Who knows? You just might be surprised at the end of the day.

Note: For the following discussions want to run our various projects inside of a localhost HTTP web server. If you have a local Apache or IIS setup you may wish to use this by putting the files that you create in the upcoming tutorials in a directory created inside the www folder. Another quick easy implementation is to just pull down the Node.js http-server module by running the following from your command line…

$ npm install -g http-server

From there you can create a directory anywhere you like and run the following…

$ http-server

This will run an HTTP server at localhost:8080. If you got to https://localhost:8080 you should see something there that tells you a server is running.

React is a view rendering JavaScript library that is created and maintained by a team of engineers at Facebook. It is responsible for dynamically handling the visual display of various components within a web site or web application in a flexible, efficient, and interactive manner. What this often means is that React handles the displaying of the data that underlies an application and will dynamically update everything that it needs to in a performance conscious manner when that data changes. We will look at all of React’s various components that come together to make this happen in greater detail as we go along in the upcoming tutorials.

Perhaps the best thing to do is to jump right in and get our first look at React. To start out we will need an index.html file. So create a new file in a directory where you want to run things from and create a file called index.html. In this file place the following code…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>

</body>
</html>

So we are first loading up the React library over CDN and we are also loading up something called the “JSXTransformer.” React has its own programming language called JSX. It is React’s own special easy-to-read abstracted syntax that in the end gets converted to native JavaScript. It is important to note that using JSX is optional. It is not required to create React applications and you can write your React components in native JavaScript if you so choose. For a lot of the upcoming examples provided in what is to follow, we will look at the same code written in both JSX and native JavaScript and you can decide which is more appealing to you. We will discuss the pros and cons of leveraging JSX bit later on as well.

Hello World in React

So now that we have React loaded up, let’s write our first React component. We will do the obligatory “Hello World” example that has so ubiquitous throughout programming tutorials since the dawn of time. We are going to personalize this a bit more though and we are going to say “hello” to an individual rather than the entire world.

JSX

So let’s start by looking at the JSX syntax just to get a look at it. Create a folder called “js” and create a file called hello.jsx and include it after the scripts like so…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
    <script type="text/jsx" src="js/hello.jsx"></script>
</body>
</html>

In this file add the following JSX code…

var HelloMessage = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<HelloMessage name="John" />, document.body);

Now let’s open this index.html in your favorite browser in your web server. You should see the message “Hello John” displayed. Congratulations, you have just written your first React component!

Read More »

, , , , , ,