HTML5, CSS3, jQuery, JSON, Responsive Design...

Steam Link and Controller shipping to Australia now!

Michael Brown  December 27 2015 07:15:10 PM
... and possibly in other countries too.

I’ve been after one of Valve’s new Steam Link devices and one of their Steam Controllers for ages now.  It was initially released in the USA only and whenever I open Steam, it always says “Coming soon”.  The official release date for Australia is supposed to be Feb 2016.

So I was quite surprised when I came across a forum comment (can’t remember which forum now) where an Aussie user said he'd simply ordered a Steam Link from hardly ever ships electrical or techie stuff to Australia, so I assumed that he must have used a third party mailing service, such as ShipItTo or PriceUSA, to get around Amazon’s geographical restrictions.

But he didn’t.  I know because I just ordered one myself!  I have a shipping confirmation and an arrival date of Jan 11 for one Steam Link and one Steam Controller.  As part of the Amazon order I was also emailed activation codes for 1 copy of Counter-Strike: Global Offensive and 1 copy of Left 4 Dead 2, yes, they worked.  Well, the Counter-Strike one did.  I already had Left 4 Dead 2.  I don’t know if these codes are transferable to another Steam subscriber.

  I’ll post a review  of both items when I’ve tested them out.

Parallel Ajax calls

Michael Brown  October 10 2015 01:23:17 AM
Some time ago (4+ years, yikes!) I wrote a post called Getting around Domino’s Ajax lookup restrictions.  In that post I outlined a way of breaking up a big Ajax call into a number of smaller ones, using recursion.

While this approach works, it does have a serious drawback: it's slow.  That's because with my recursion method, the Ajax calls had to run in sequence.  The second Ajax call was triggered by the .success() callback for first Ajax call.  Then the third Ajax call would be triggered by the .success() callback for the second Ajax call.  And so on.

It turns out that there's a much neater way of achieving this in jQuery, by using promises.  Here's the code:

).then(function(data1, data2, data3) {
  console.log("data1 = " + JSON.stringify(data1[0]));
  console.log("data2 = " + JSON.stringify(data2[0]));
  console.log("data3 = " + JSON.stringify(data3[0]));

I've lined up three Ajax calls inside my $.when() call.  The chained .then() call is triggered when, and only when all three Ajax calls have completed and returned their data.  The returned data from each Ajax call is then passed into .then(function()) as variables in sequence; three Ajax calls so three data objects returned.  Nice and simple.

NB: the data objects returned the my function inside the .then() are actually arrays, of which the first member is the JSON data in which I'm interested.  Hence "data1[0]", "data2[0]" etc when I reference them.  (FYI, the second array member is the return status, and the third is the native XHR object.)

bindAll function for ES6 classes

Michael Brown  September 14 2015 05:48:32 AM
I've written a simple JavaScript function to bind multiple methods to an ES6 class's 'this' object.


The problem is that an ES6/ES2015 class method's context is not autobound to the class's object. This is a particular point of pain for ReactJS when using this syntax. (ReactJS's previous .createClass() syntax did autobind a component's methods to the component's own context.)  So in the code below, the close() and open() methods, which both call this.setState() will fail. This is because those method's this object is not autobound to the component's context, so this.setState() simply doesn't exist.

class ExampleModal extends React.Component {
constructor(props) {
close() {
  this.setState({ showModal: false });
  this.setState({ showModal: true });

You can bind all the methods manually in the constructor to get around this problem, but that's a massive pain to remember to do that, not to mention a lot of extra lines of code in your constructor.

How To Use es6BindAll

So I wrote the es6BindAll function to do it for you.  Those of you that have used Backbone.js can probably guess that this is inspired by Backbone's bindAll function.

You simply supply the function with the context object as its first parameter, then an array of method names that are to be bound to the object. Note: those methods must exist in the current component/class, i.e. they can't be external functions.
Example use:

import {es6BindAll} from "es6bindall";

class ExampleModal extends React.Component {
constructor(props) {
  es6BindAll(this, ["open", "close"]);
close() {
  this.setState({ showModal: false });

  this.setState({ showModal: true });

Browser Support

Supports Internet Explorer 9 and upwards, plus all good browsers (i.e. any browser not called Internet Explorer).


To install via NPM:
npm install es6bindall

Here's links to the packages on npmjs and github:

Update December 2015

I've subsequently updated es6BindAll so that you can import it as the default, i.e.
import es6BindAll from "es6bindall";

import {es6BindAll} from "es6bindall";

will continue to work.

I've also added some proper tests, using Mocha and Chai (I know, like I should have done in the first place!).

ReactJS list sorting with jQuery-ui

Michael Brown  August 30 2015 09:50:39 PM
A simple, sortable list implemented using ReactJS and jQuery-ui's sortable() method.


Although there's a number of drag and drop modules for ReactJS, they all seem to use the HTML5 drag and drop API for which browser support is still sadly lacking.  E.g. the documentation for the React DnD module says the following:

React DnD does not work on mobile browsers yet because it currently relies on the HTML5 drag and drop API which no mobile browsers implement.  -

jQuery-ui seems to have fallen out of favour recently, but it still has the best drag and drop (and sortable) UI that I've seen.  But how to combine it with ReactJS?  The raison d'etre of both libraries is to control the UI!  But they can't both do it; I've had ReactJS throw warnings at me when my other code has tried to monkey with the UI without its knowledge.


The trick to getting them to work together was to not let jQuery-ui modify the UI at all, but only *appear* to do so.  All we want from jQuery-ui is the mechanics of the sortability.  In other words, we read its (and the user's) intentions, and then pass those to ReactJS to do the actual sorting.  This is possible because jQuery-ui's sortable() method has a cancel call that sets the UI back to how it was.  Here's the basic workflow then:

1. Attach the jquery-ui.sortable() method to a list of line items
2. Let the user drag and drop those line items to re-order them.
3. When the user starts dragging, we read the index of the line item (s)he's dragging
4. When the user drops the line item, we:
a. Read from jQuery-ui.sortable)() the new index position for the line item
b. Cancel jQuery-ui.sortable() so that the list goes backs to its original position, and the UI is unchanged.
c. Pass the old and new indexes of the dragged line item to ReactJS.  ReactJS then reorders the back-end data and calls a setState(), which re-orders the list in the UI.

Advantages & Disadvantages

The major advantage is that it actually works!  And works everywhere, including mobile (courtesy of the jquery-ui-touch-punch plugin).

The disadvantages are that ReactJS plus jQuery plus jQuery-ui is a pretty heavy set of dependencies, even when minified.  You can, however, cut jQuery-ui down to just the essentials needed for its .sortable() functionality.

Libraries and Build Tools

The sample list app requires ReactJS, jQuery and jQuery-UI as run time dependencies.  It's written in the new ES6, or ES2015 as it's now called, syntax using the module pattern.  So it requires Webpack and Babel as build tools.

To Install

Clone the github repository  In a terminal, cd to the folder that you just cloned the repository into and run  
npm install

You can build the app with either:
npm run build

npm run buildwin

The latter minifies and uglifies the resulting JavaScript libraries, which reduced to about a third of their unminified sizes.  However, build time is significantly higher!

Open the build/index.html file via a local server.  SublimeServer is good if you're running SubmlimeText.  Otherwise you can run:
npm run start

to start up webpack-dev-server.  When this is running, your test URL is http://localhost:8080.


    Windows 10 install. How things have changed...not!

    Michael Brown  July 30 2015 02:50:19 AM
    I'm attempting to install Windows 10, more fool me.  Sadly, I downloaded a game from Steam recently - Wolfenstein The New Order since you ask - that only works on Windows 64-bit!  It seems that there's a number of games with this requirement, and they're only going to grow more prevalent.  So I thought, if I'm going to have to install a new version, I may as well get the latest.

    I was hoping against hope that Microsoft might have improved its installer since Windows 7.  (I skipped 8 and 8.1 for obvious reasons.)  But no.  I soon ran into this error from the Windows 10 install CD's partioner:

    "We couldn’t create a new partition or locate an existing one."

    I should have known what the problem was, since I wrote about it only a couple of years ago.

    Yep, Windows still won't play with other operating systems and installs.  Once again, I had to disconnect every internal drive from my system except for the one on which I wanted to install Windows 10.   Only then could I get past this error.


    On the plus side though, Windows 10 doesn't need an install CD just so I can get the the internet over my wired Ethernet connection, like Windows 7 did!

    Basic React Tutorial - Part 2

    Michael Brown  April 18 2015 12:05:33 AM
    As threatened in my previous post, Basic ReactJS Tutorial, I've now updated my sample ReactJS checkboxes app into "a kind of questions and answers, survey form thing".

    This post will walk through the steps that I went through to achieve that.  As you read this explanation, I hope it comes across to you just how easy this was for me to do.  Not because I'm any genius coder, or even that much of an expert in ReactJS yet.  It's just the way that ReactJS leads you into developing your app, especially the compositional, component based design that it encourages.  While it would be a stretch to say that the code wrote itself, it did pretty much design itself.  That's to say that before I sat down to type a single line of code, I already knew pretty much how I it was all going to break down.  In ReactThink (and I may just trademark that term) it means that knowing the components that created in my from the previous exercise, I just needed some higher level ones to put those existing components to work a bit more.

    CheckBoxInputFields Component

    The highest level React component that I was left with from my previous exercise was CheckBoxInputField.  This component groups together a number of CheckBoxInput components, to give us a "field" of HTML input elements of type "checkbox".  The number of elements in the field is determined by the array of data (or props) that we passed into the CheckboxInputField component.

    The next step to turning this single question in to list of questions - i.e. a survey - is to create a new React component called CheckboxInputFields.  The clue to what it does is in the name, or is intended to be so anyway!  CheckboxInputFields is a plural of CheckboxInputField, so guess what it does?  Yep, the CheckboxInputFields component renders a number of CheckboxInputField components.  How many CheckboxInputField components the CheckboxInputFields component renders is determined, once again, by the array data that is passed into it as props.

    Enough blurb.  Let's look at some code.

    Example 1 - React Survey App, state in wrong place

    You'll see that my source data is now an array of questions and answers, stored in the global variable, questions.  This data is passed into the CheckboxInputFields component, as props, by another React component called SurveyApp (of which more later).  The CheckboxInputFields component's render method maps through the questions array and creates a new CheckboxInputField component for each member, passing that member down as props to each new CheckboxInputField.  Each CheckboxInputField component so created is pushed onto an array variable called mappedInputFields.  Finally, the mappedInputFields variable, which is now a collection of CheckboxInputField components, is rendered via the return statement.

    I've no idea how easy that all looks to you, but I can tell you it took me about two minutes to type it out, and it ran perfectly the first time.   Furthermore, it did so without me having me to change anything in the CheckboxInputField component.  In fact, I'm not sure that I even had to look at the CheckboxInputField component!!!  I knew what that CheckboxInputField component does and what its props were from last time, so no real need to look at it again now.  Cool as!

    (Actually, I did modify CheckboxInputField later on, to have it render the question - or the blurb property as I've called it - just before the list of answers.)

    That pesky state again

    In my earlier post, I said the following:

    This is one of React's underlying principles: state should be handled at the highest level possible in your application.  High level state is then passed down to lower level components as props.

    Is that how state - i.e. are the checkboxes checked or unchecked? - is being handled in this new version of the app?  Most definitely not!   The state is still being handled down at the CheckboxInputField level.  The CheckboxInputFields component has no easy way of knowing whether any of the CheckboxInputField components that it created have been checked by a user.  Once again, the state is being handled at too low a level.  State needs to be handled at the CheckboxInputFields level.

    Or does it?

    Thinking ahead, what if we want our app to display a collection of CheckboxInputFields components?  In other words, we want a survey to consist of a collection of different groups of questions, each grouped by a theme or topic?  In that case, our state would again be at too low a level if it were handled in the CheckboxInputFields component.  We've have to refactor yet again to move the state to our new, higher level.  So let's skip that mistake and do it right first time, this time.

    If you want something done, then go to the top!

    I only have one CheckboxInputFields element in my Example 1 version above, but I never intended to handle state within it.  Instead, I've created a higher level React component, which is the SurveyApp component.  In Example 1, all it does is render my one CheckboxInputFields element with the necessary props, and nothing more.  But it was my intention from the beginning to handle my state in this top most element, so let's do that now.

    Example 2 - React Survey App, state in correct place

    In Example 2, state is handled in the SurveyApp component.  The state data is updated and setState() call is made within that component.  A setState call causes the SurveyApp to re-render, which causes the whole app to re-render, like so:

    SurveyApp -> CheckboxInputFields -> CheckboxInputField -> CheckboxInput

    With each CheckboxInputFields owning multiple CheckboxInputField components, and each CheckboxInputField owning multiple CheckboxInput components, the diagram of re-renders would actually look like a pyramid.  (I just couldn't be arsed to draw one!)

    And if you're thinking "re-rendering the whole app = performance nightmare", remember that React's virtual DOM and super fast diffing engine mean that this isn't the case.

    Passing the buck upwards again

    In order to have the SurveyApp component handle the state, I did have to rewrite the lower level components to ensure that the when events are triggered down there (i.e the user checks or unchecks a checkbox) the relevant information from that event reaches up to SurveyApp level.

    CheckboxInput required no changes because it was already passing its state changes upwards (to CheckboxInputField).

    CheckboxInputField gets the biggest rewrite because this is where we were handling state previously.  So, its getInitialState() method is removed.  Instead of looping through the (now non-existent) state array, its render() method now maps through an array of passed in props.  CheckboxInputField's handleFieldChange() method, which was resetting the state earlier, now simply passes the relevant data, with a little preprocessing, back up to CheckboxInputFields via the supplied (via props) callback function, i.e. this.props.handleChange().

    CheckboxInputFields does even less with that data!   There's no equivalent handleChange() or handleFieldChange() method in CheckboxInputFields.  The callback function that was passed down from CheckboxInputFields to CheckboxInputField is actually one that was originally passed from from SurveyApp to CheckboxInputFields.  So when the new event data is heading back upwards, the CheckboxInputFields component simply hands it on up to SurveyApp.  Think if of it as like how a passthrough server works.

    Finally, the new event data gets all the way up to SurveyApp's handleFieldChange() method, where the state is reset.  The method uses two passed up indexes, the index of the question where an element has been (un)checked and the index of element (i.e. which answer) within that question, to determine which data point to change.  The change is to add a .checked property if the underlying checkbox field has been ticked, and to delete that property if the field has been unticked.   Once the relevant data point is modified, we call a setState(), so re-rendering our whole app, and our work here is done.

    Netflix and Chromecast

    Michael Brown  April 13 2015 04:36:22 AM
    I signed up to the Aussie Netflix a couple of weeks ago.

    To be honest, I’d expected to be completely under whelmed by the content available, especially knowing what was available in the U.S. Netflix store.  But while it’s still only a fraction of what our American cousins get, there’s still a lot of good stuff in there.

    For example, we’ve just finished the second series of The Fall, and I’ve started again on Lost.  I was disappointed that there was no Breaking Bad, like the Americans have, but then I made an interesting discovery almost by accident.  It seems that Netflix serves up its content based upon where you are geographically located, rather than upon where you registered your Netflix account.

    Let that sink in a minute...

    If you take a trip to the U.S., and you have your Aussie iPad, with your Aussie dowloaded copy of the iOS Netflix app, which has your Aussie registered user name and password in it, then you’ll see U.S. Netflix content, not Australian.

    Now if only there was some way to make your PC, tablet or phone think that you’re in the U.S. without you actually having to fly there….


    I started off playing Netflix though my Home Theatre PC (HTPC).  This is a bit of beast that I put together about in 2010, principally in order to record that year’s Football World Cup.  (Our Foxtel box at the time was unable to record terrestrial stations, due to limitations of the wall wiring at the unit where we were then living.)

    The HTPC has done its job... just about.  It’s been a nightmare to setup and keep going, which I put down to one thing: Microsoft Windows.  Windows 7’s Media Centre works well enough when it works at all, but there’s been far too many times when it just doesn't.  I’d try and watch something that I thought I’d recorded, only to be greeted by a blue screen, or a boot error or an update error - i.e., all things that we know and love (not much) about the world’s most “popular” operating system.

    Trying to control Netflix through the HTPC is fiddly at best.  Apparently, there’s a Media Centre plugin for Netflix, which I’ve not tried.  I’ve been using it through a web browser, which is less than ideal on a TV screen.  Plus the HTPC is too big to go in our new entertainment cabinet, so its days are numbered anyway!

    Which led me to get a Chromecast.  They’re currently $43 at Harvey Norman, but sadly the one in the CBD, at Martin Place, appears to closed down now.  I managed to get one a Dick Smith for $46 though.

    So far, my experience has been overwhelmingly positive, although with major one downer that I’ll to later.

    First, it’s a breeze to set up.  You plug it into a spare HDMI socket on your TV or preferably, your surround sound receiver if you have one (more on that later).  You’ll need to power it up via a USB charger via a supplied micro-USB cable.   I was able to plug the USB into my TV’s USB socket for power, and the supplied cable was still long enough to stretch to my receiver.  If you don’t have that option, there’s a wall-mounted USB charger supplied in the Chromecast box too.

    Once plugged in, and with your TV set to the appropriate HDMI input, you setup your Chromecast via a PC, Mac, tablet or phone (Android or iOS).  You’ll need to download an app for whichever platform you’re using.  When you run that app (and I used the Mac version) it locates your Chromecast automatically.  I’m not sure how it manages this little trick, because you’re Chromecast isn’t on your network yet!!!   In fact, that’s the first thing your Chromecast setup app will ask you to do once it’s found your Chromecast: fill in your wifi user name and password to get your Chromecast on your network.

    Remote Control (lack thereof!)
    That’s about it for the setup.   So, how do you play stuff on it?  There’s no remote supplied for your Chromecast.  You’ll have to use your own device - PC, Mac, tablet or Phone - as the remote.  Don’t worry, that’s not as bad as it sounds!

    I’ll explain how to do it for Netflix.  First, you need to download the Netflix app if you’re using a tablet or a phone.  If you’re using a PC or Mac then you need to download an extension for the Chrome browser (and only the Chrome browser will work) before navigating to the site.

    Find the program you want to play and start playing it whatever device you’re using, then click on the Chromecast icon.

    The program you started playing should then start showing on your TV screen rather than your controlling device.  You can pause, rewind fast forward your program on your device and that will control what happens on your TV screen through your Chromecast.

    Chromecast's Internet Connection

    At this point you might be thinking, as I did, about what happens if you were to switch your controlling device off.  I was using my iPhone for this, and the iPhone had some updates that it needed, one of which required a reboot.  I let this process go though, fully expecting the Chromecast program that was currently playing to stop at that point.  But it didn’t.  It just kept on playing.  “The Chromecast must have cached some content”, I thought.  But 20 minutes later, and with no further communication to it from my iPhone, the Chromecast was still playing the Netflix content!!!

    It seems that the Chromecast has more to it than I originally thought.  Although it’s touted as a device that lets you “cast” content from your device to your TV, there’s more to it than that, at least for Netflix and other Chromecast-enabled services.  When you start playing Netflix content from your phone to your Chromecast, the latter actually makes its own direct connection to the internet to do the streaming.  The content doesn’t go through your phone.

    All of which is great, because you’re then free to do whatever with your phone or tablet, without worrying that it’s going to break off your Chomecast/TV content!  You only need to return to the Netflix app on your phone when you want control it further - e.g pause it.  Be warned though, when you do return to Netflix on your phone, there is often a very long delay while it syncs to where your Chromecast has actually got to with your program.  You’ll see the progress bar for your program on the phone leap across to the new location when that sync has happened.  After that, you can pause rewind etc.

    Which brings me to the one major downer.  Because the Chromecast makes its own connections to the internet for the like of Netflix, it does not work with VPNs.  If your VPN on your iPad, for example, is set to the U.S., and you try to play an episode of Breaking Bad, well sorry, that’s not going to work.  The Chromecast isn’t getting its content through your iPad's VPN, so it’s not going to able to see that U.S. content.  You may able to do something by changing your router’s DNS settings, but I’ve not tried that yet.

    Surround Sound

    Does the Chromecast do surround sound?  Does it ever!!  Not Dolby Digital, but its HD big brother, Dolby Digital Plus!

    Here's what I see on my Denon receiver panel when I'm watching Lost through the Chromecast:

    Dolby Digital Plus from the Chromecast

    There's just something so sweet when that blue HD diode lights up!!

    I didn't have a spare HDMI input on my receiver, unfortunately.  I had to unplug the HTPC for the time being.  I managed to pick up a remote HDMI switcher from Jaycar, which gives me another two inputs.  I can even control that as part of an Activity on my Harmony One universal remote, so I don't have to keep switching it manually.

    Basic ReactJS Tutorial

    Michael Brown  April 3 2015 10:15:00 PM
    Of JavaScript Frameworks
    To say that JavaScript Frameworks have been in a state of flux in the last few years would be a truism.  Every developer seemed to zero in on jQuery and/or Bootstrap, and those two have proved to be stickers.  But then followed Backbone, Backbone+Marionette, Amber/Ember and Angular, each one the flavour of the month in a dizzying succession.  I often felt that I was spending more time attempting to learn the strengths and weaknesses of each JavaScript framework than I ever did actually writing any code in them!!

    I still have a soft spot for Backbone.js, which was the first JavaScript framework at which I looked. If it doesn't do all that much for you as a developer, it's still a great way of organising your code, and its models rock! I like the way you can use as much of Backbone or as little of it as you wish, making it easy enough to add to an existing project, not just new ones. Too many of the other frameworks which I looked seem to take a "my way or the highway” approach, requiring you to rewrite everything from scratch.  You had to follow that framework's own ideology (for want of a better word) and forcing you to subscribe to its own idiosyncrasies.  Anything that you wanted to do that wasn't of its particular box seemed to be a massive pain.

    Also, many of those other frameworks did not actually make much sense to me.  I tried my hardest with Ember.js and especially with Angular.js, but could not wrap my head around either of them.

    Angular’s “directives embedded in HTML” approach, in particular, put me off in a big way. It just didn't look right to me, and still doesn’t.  And from what I've read in various forums, the two way data binding that is one if Angular's big selling points seems to cause as many problems as it solves, especially when applications scale to larger sizes.

    Angular sure has a lot of developers using it.  How many of them still like it now is another question.  Backwards compatibility does not seem to be one of its core strengths.  I’ve seen the up-and-coming Angular.js 2.0 described as a "course change", a description that should send a shudder through any developer that's relying on it. How many of those developers are going to take kindly to rewriting their entire code base from scratch, I wonder? I think many of them may just look elsewhere instead.

    In fact, I believe the Angular.js is heading for a demise that’s going to be even more rapid that was its original rise. Maybe I'm being too hard on it; and I’m not an Angular guy, after all.   Angular people can make their feelings known in the comment section of this post if they feel inclined!

    Enter ReactJS

    For my money, Facebook's ReactJS JavaScript library is set to dominate the Web programming world over the next year.  Even if it doesn't get as many developers as Angular or Ember, the latter two libraries are rapidly assimilating many of React's best ideas, so React will win out one way or another.

    React's best features:
    1. Encourages component-based design based on composition.  Practically mandates it, in fact!
    2. Implements a one-way, top-down data flow.
    3. Has a super fast diffing engine that minimises updates to the DOM (always a performance pain).

    The Tutorial

    I'll attempt to demonstrate these features by a way of a small tutorial.  In this tutorial, I'll be setting up a simple, checkbox Input field.  (I said it was simple!)  But I'll set it up as a React component, to which you pass in parameters (called "props") and manage the state of that field (called, ermmm.. "state" in React!).

    By "field", I mean a collection of Input fields of course, because that's how checkbox and radio fields are defined in HTML: as a collection of Input fields, grouped by their Name tag.

    Let's start with an individual checkbox box element, as you might set it up in React

    Example 1 - Single, Uncontrolled Checkbox Element

    We start with CheckboxInput, an instance of the React class.  The class implements a single method, called "render".  This method must be supplied for every React component (the only method to be so mandated).  As you've probably guessed, the render() method tells the React component what to render as its final output.

    But what's that stuff inside the render() method's return brackets?  Raw HTML?  What's that doing there?  That stuff's not legal there, surely?!!


    What's actually in between the render() method's return brackets is something called JSX.  As described by Facebook, "JavaScript syntax extension that looks similar to XML".  I actually don't think it looks anything like XML, which is a good thing in my book, as I happen to loathe XML.  (Wake up!!  Use effing JSON!!!)  But I digress...

    Think of JSX as a way of letting you embed raw(ish) HTML directly in your JavaScript.  It's a convenient alternative to creating a JavaScript string out of HTML to return as your output.  Does this kind of code look familiar to you?

    var returnHTML = '<label><input type="checkbox" name="' + varName + '" value="' + varValue + '" \/>' + varLabel + '<\/label>'

    Did I get all the double and single quotes in the right order there?  Because just one of those babies out of place and I'm stuffed, right?  Oh and you did know that every forward slash that appears in a JavaScript string has to be escaped with with backwards slash, yes?

    Look at that code, and compare it again to the JSX in my first JSFiddle above it.  Which one makes it easier to understand what's going on, would you say?

    JSX has other benefits too, which I'll come to later.  But for now, you should be aware that there's a cost to using JSX.  Obviously, the browser won't understand it because it's not standard JavaScript.  So, you must add a translator (or "transpiler") file called JSXTransformer.js to your project.  This file transpiles JSX to standard JavaScript on the fly, so the browser can understand it.  Yes, there's a pre-processor available so you don't have to include JSXTransformer.js in your production code.  But for development, and this tutorial, JSXTransformer is fine.

    Back to Example 1 in the JSFiddle above.  After creating my CheckboxInput component, I set up some data to pass to it (the question variable), before finally calling the React.render() method to render the component.  The React.render() method takes two parameters.

    The first parameter is the name of the component to render, written like an HTML tag.  Within that tag, you can pass down any number of parameters to the React component.  In React parlance, parameters passed down from to an "owned" component like this are called "props", which is short for "properties".  Note that props are said to be immutable.  They are not to be changed by the lower level component once passed down from above.  More on this later.

    The second parameter the React.render() method takes is a JavaScript representation of the HTML element upon which the component is to be rendered.  (If you don't supply the second parameter, then the component will render on the page's Body tag.)

    Phew!  That was a lot to go through just to get a single, input checkbox element on the page!  And one that's really doesn't do much for us either.  By which I mean, you could have done just as easily, probably more so, if you'd just used a bit of jQuery and HTML.

    In particular, there's no state being monitored here.  By which I mean, if you wanted to find out whether the element was checked or not, where would you look?  There's nowhere our React code that tells you.  At the moment, you'd have to query the DOM directly to find that out, using a bit of JavaScript, and that's a big no-no.

    So let's start getting React to do some more work for us.

    Controlled Vs Uncontrolled

    In my first example, I called my checkbox element "uncontrolled" in the title.  What does this mean?  It means what I was referring to in the previous paragraphs: i.e. that React isn't doing anything with the checkbox element in the CheckboxInput component, other than its initial render.  After that we're on our own.

    With a "controlled" element, its parent React component takes care of its state and all of its updates, not just its initial render() as we had it in our first example.  See the React doco on Forms for more info on this subject.

    In Example 2 below, we'll take the first steps to making our checkbox element a controlled one.

    Example 2 - Single, controlled Checkbox Element, No State Update

    In example 2, we've made two additions.  First, we've set up an initial state for the component, via a getInitialState() method call.  This another special React method, like the render() method.  This method must return an object that is to be the initial state of the component.  Very often, the initial state is taken, in part at least, from the props that were passed down to the component.  That's what we have done here, taking the checked parameter from props and creating a checked state from it.  (Remember, the props themselves are immutable; they should not be changed within the component that received them.)

    The second addition is that we are now setting the input's checked state from the React component's checked state.  This is the line checked={this.state.checked} within our Input JSX does.

    There's a step that I've deliberately left out of Example 2, however.  Before I add that step (in Example 3) I want you see what is the result of omitting that step.  Switch to the Results tab for Example 2, and then click on the "Apples" checkbox a few times.  Did you see what happened?  Absolutely nothing!

    And that's as it should be.  Because we're now having the React component set the input element's "checked" state from the React component's own state, i.e. this.checked.state.  And the latter is always set to false in our code as it stands now.

    Let's fix that now in Example 3.

    Example 3 - Single, controlled Checkbox Element, With State Update

    Two more additions here.  The first the onClick={this.handleClick} click handler line that we've added to the Input JSX.  What's that?  A click handler set up as an HTML event attribute?  Aren't we supposed to all be using JavaScript events now?   Don't worry; we are!   What you see here isn't actually an HTML event attribute.  It just looks like one for familiarity's sake.  (An actual click handler event attribute would be in all lower case: "onclick", not "onClick"!)  Once it's been through the JSXTransformer transpiler, it will be a JavaScript event.  In fact, it will become part of one big, delegated JavaScript event, along with any other "event attributes" that you might have set up in JSX.  All this you get for free, and you don't even have to think about it!

    The second addition is a method that will be called by our new click handler.  I've called this method handleClick() (although we could have called it anything).  Let's take a closer look at what's going on in that method:
    handleClick: function(e) {

    The setState() method is another built-in method for a React component.  It set's the components internal state for the parameters and value supplied.  In this case, we set the React component's internal checked state to match whatever the input element's state has been set to (by the user clicking on it!) which is what we want.  (FYI, the e parameter that we've passed into the handleClick() method is an event, or to be more precise, a "synthetic event"; one which has all browser inconsistencies smoothed out.)

    But the setState() method does more.  Any call to the setState() method causes the component to re-render.  Let's say that again, because it's important.  Any time you make a call the setState() method, your whole, stinking component is going to re-render onto your page.   Wow!  How crazy is that!!  I mean the performance problems alone make the dumbest thing that you could possibly do, right?

    Actually, wrong.  React's superfast diffing engine, with its "shadow DOM" or "virtual DOM" feature takes care of that.  Only the parts of the DOM that really need to change are actually re-rendered to the real DOM.  And any such renders are automatically batched up, so your performance won't take a nosedive into the compost.  (This is one of those features I mentioned that the likes of Angular and Ember are now planning to add to their own frameworks.)

    Here's the proof that our checkbox input is now controlled.   Switch to the Results tab for Example 3, and then click on the "Apples" checkbox a few times again.  The checkbox should now update correctly.  More importantly, the element's current DOM state is now in sync with the React component's internal checked state.  You can check this in your favourite JavaScript debugger.  Here's how it looks in the Chrome debugger, and you can see how the DOM state of the checkbox input matches that of the React component's this.state.checked.

    this.state.checked in the Chrome Debugger

    From Element To A Field

    A single, checkbox element can be useful - think of a "Please accept these terms before proceeding" tickbox, for example.  More often that not though, you'll be wanting to present users with a range of checkbox options from which to choose.  I'll refer to such a collection of checkboxes as a "field" from this point on.  As I said earlier, a "field" in this tutorial is a collection of checkbox inputs, grouped on their name tags.

    Example 4 shows how I've created such a new field-based React element, which I've called CheckboxInputField.

    Example 4 - Controlled Checkbox FIeld, Poor State Implementation

    If you read through the code of the new CheckboxInputField component's render() method, you can see the basic approach.  We loop through a supplied array of checkbox options (courtesy of a rewritten question variable) and return an array of CheckboxInput components.  This simple composition technique is, as I said in my introduction, one of React's key strengths.  We already have a tried and tested component, in the CheckboxInput component.  See how easy JSX makes it to compose a number of those components, before passing them to CheckboxInputField's own render() method, as the mappedInputElements array variable.

    I've also included an attempt at state management in Example 4, in the form of the getRefsState() method.  The approach that I've used is a deliberately poor one, which I came up with before I'd really got my head around the way ReactJS works and what its intentions are.  (Example 5 below shows a better way to do this.)  This method works by querying each of the "owned" CheckboxInput components, in turn, to find out what each one's state is.  The see how the CheckboxInputField component is tied to its "owned" CheckboxInput components via the this.refs property.  This a pre-built React property.  In order to make use of it, you need to supply a ref value to each new, "owned" component as you are creating it, which I've done in "ref={data.value}" line in CheckboxInputField's render() method.

    Although this method of state management will work, it has a major flaw: the state is in the wrong place!   If you want to know the state of CheckboxInputField component, then the state should really be held within that component.  And not in the half-assed way that I've done it, where the CheckboxInputField has to query each of its "owned" CheckboxInput components in order to determine its own state.  In truth, the individual CheckboxInput components don't even need to know what their own states are.  Their individual states only have validity insofar as they are part of the CheckboxInputField component that owns them.

    This is one of React's underlying principles: state should be handled at the highest level possible in your application.  High level state is then passed down to lower level components as props.

    So, let's put the state in the CheckboxInputField component in Example 5.

    Example 5 - Controlled Checkbox FIeld, Better State Implementation

    First, let's look at the change to the CheckboxInput component.  We still have a handleChange() method, but it doesn't do anything with the CheckboxInput component itself; certainly not setting state in there, because state is no longer handled at that level.  (And for that reason, we can also lose the CheckboxInput component's getInitialState() method.)  All the handleChange() method does now is pass some values up to its owner CheckboxInputField component.  It does this by calling the latter's handleFieldChange() method, which was passed down as a callback funciton in the CheckboxInput component's props.  This is the line "handleChange={that.handleFieldChange}" in the CheckboxInputField's render() method.

    The CheckboxInputField component now gets a getInitialState() method, because that's where we're holding the state now, remember.  At this level, of course, we need to hold the state as an array, which I've called values.

    The CheckboxInputField component's handleFieldChange() method is, as I said earlier, called as a callback function from within each owned CheckboxInput component, when its element is clicked by the user.  Again, the state that we're dealing with at this level is an array, so we have to take care to update the correct member of that array!  The index parameter passed up from the call from within CheckboxInput call takes care of this.  This index was, in turn, passed down from CheckboxInputField to CheckboxInput as another prop, in the line "index={x}".

    Gravy!  Now we have what we wanted: state is handled at the CheckboxInputField level, giving us one place to look for the state of our field:

    State handled at the CheckboxInputField level

    Beware that when passing objects (and arrays are objects in JavaScript), as function parameters, they are passed by reference.  So if you're updating such objects within your function, you do need to make a copy of them first (I've used a .slice() call here to do that) otherwise you'll find yourself inadvertently updating the original object too.  This can have serious repercussions for a ReactJS setState() call, for example.

    Future Enhancements

    One checkbox field like this is just dandy, but what if we wanted a group of such fields?  You know, as a kind of questions and answers, survey form thing?

    Well, thinking in the React way, we could create a new component called CheckboxInputFieldGroup.  This could take an array of questions and answers as its data props, and in turn, could pass that data down to an array of CheckboxInputField components that it would create.  It's that design by composition again!

    There's a problem though: where would the state for a CheckboxInputFieldGroup component live?  At the moment, our state is in the CheckboxInputField components.  Damn!  Now it's a too low a level again?  "Will that boy never learn?"

    Yes, we would have to refactor things to move the state higher up again.  Ideally, to higher level than even the CheckboxInputFieldGroup, to save us refactoring a third time, when we decide that level isn't high enough either!  Really, you need to be thinking at holding state at the top application level, where you deem that level to be.  The React Facebook people have an entire design approach, called Flux, to help you with that.  Flux is beyond the scope of this tutorial, however, and to be honest, I've lot looked to deeply into it myself, as yet.

    Update 18/04/2015

    As threatened above, I've written a Part 2 to this tutorial, where I expand the app into a "kind of questions and answers, survey form thing".

    Chromebook auto-update - stop, already!!!

    Michael Brown  April 3 2015 09:04:43 PM
    Of Chromebooks
    I sure do love my Chromebook!  (I got the 2013 Samsung, ARM-based model.)

    If you can live within its limitations, it’s a more than serviceable companion on the road.  I mean, a 9 hour battery life, and pretty much guaranteed to be virus-free, all for under $300?  (Yes, I know that they’re nearer $200 in the U.S. but I don’t happen to live there.  I have to pay the inflated, “Australia Tax” prices.)

    About those limitations:
    • It doesn’t run Windows or any of its applications.  Everybody will have their own opinion as to whether this counts as a limitation or as a blessing in disguise!!!

    • Severely limited printing abilities.  That’s “limited” as in non-existent, unless you happen to have one of the small list of printers with which Google’s Cloud Print service is compatible.

    • A small (but growing!) number of Chrome apps that will work offline.  This is not the problem that it was a year or two back.  Gmail, Google Calendar and all of the Google Drive apps now work offline.  You just need to remember to offline enable them, and you will need an internet connection to do that.  For all the detractors that are still holding this problem against Chrombooks, I would say try giving the average user a Windows laptop with no internet connection, and let’s see how productive they are with that!!

    You can work around many of these limitations by installing a full Linux version alongside ChromeOS.  Sure, this is cheating in a way, but no more cheating than I have with any Windoze PC that I’ve owned in last eight years.  Google “chrome linux crouton” for instructions on how to do this.  Note: requires Developer Mode (of which more in a moment).

    Auto-update Woes

    One undoubted problem that I’ve been facing with my Chromebook, however, is its auto-update feature.  Normally, I’d tout this feature as a good thing.  The OS keeps itself automatically up to date over the internet.  No need to bother with the nightmare that they call Windows Update.

    But damn Google for not giving users any easy way to control when and where this auto-update happens.  According to Google, ChromeOS is clever enough to sense when your Chromebook is tethered to your mobile phone, and it won’t auto-update in that situation.

    Sadly, that’s not my experience!  Just yesterday, my Chromebook chewed through over a 100 Meg of my phone’s 4G data in a matter of seconds, before I could stop it.  On another occasion, it went through 400 Meg in about a minute.  (Really, until that time I had no idea that my 4G connection could actually go that fast!)

    How To Fix

    Anyway, I’ve finally found a way to stop this nonsense, but it’s not a particularly easy way, I’m afraid.  You need to have your Chromebook’s Developer Mode enabled.  (That’s Developer Mode; not to be confused with the Developer Channel, which is something else.)  Setting up Developer Mode on your Chromebook (Google for instructions on how to do it) will power wash (i.e. wipe and resinstall) your Chromebook, so make sure any local data is backed up first.

    Assuming that you’re in Developer Mode, here's how to stop the OS from auto updating itself:
    1. Hit Ctrl->Alt->t on your keyboard, to launch a Crosh shell window

    2. Within that window, type “shell” (without the quotes)

    3. Now type ”sudo initctl stop update-engine” (again, without the quotes)

    Your Chromebook's auto-update engine should now be switched off.

    You’ll need to do this before you tether your Chromebook to your phone, obviously!

    Be warned that this setting is not "sticky".  The next time you reboot your Chromebook, the auto update engine will be turned back on again.

    Many thanks to "will" for this tip.

    React Bootstrap Slider component

    Michael Brown  March 1 2015 10:29:07 PM
    I've just written a ReactJS, wrapper for the HTML5 input type=”range” slider component, but using [seiyria’s Bootstrap Slider component] ( as a polyfill where the HTML5 version is not available (IE 9) or otherwise suffers from a problematic implementation (any other version of IE).

    The code and full documentation is available on Github.  There's a demo available too.


    I like the HTML5 native range control, especially how easy it is manipulate via ReactJS, my current favourite JavaScript library.  (I'll be writing a lot more about React in future.)  You set up an HTML5 range control like so:

    <input type="range" value="20" min="0" max="100" step="10">

    This will give a slider control, ranging from 0 to 100 in steps of 10, with a starting value of 20.  Nice and easy!

    Here’s how the native JavaScript control is rendered in my ReactJS plug-in:
    render: function () {
       return (
            <input id="mySlider"
               step={this.props.step} />

    It’s about as simple a rendering as you could want in React. You’d pass some props into your component, and render them as the corresponding attributes on the input field. Sweet as!
    But knock me down with a feather if there aren’t problems with IE.

    Internet Explorer Problems

    The first problem is that input type="range" element simply isn't supported on IE 9 and below. It will actually display as a type=”text” element, so instead of slider, you’ll get a text box with a number in it.  This is what prompted me to create a React control that would fall back to the Bootstrap Slider for browsers that didn’t support the native HTML5 element.

    The second problem is that IE10 and 11, where the control does display, doesn't respond correctly to right events when you need to track the slider value being changed.  I go into more detail on that on my Github page.  I probably could have worked around that one, but ran into my third and final problem with IE.

    The third problem in IE is that the HTML5 range control looks like crap!  It’s not just ugly, IMHO. It’s inpractical too.  Its handler (the bit on the control that you actually slide) is the same height as the rest of the slider, making it to pick out with your eye, not to mention with your finger if you’re on a tablet. (Thankfully, the latter would only ever be an issue on Microsoft tablets, of which there's next to zero in the real world).

    In the end, I made an executive decision in my React Bootstrap Slider component: I don’t display the native HTML5 slider control on IE. At least not for IE 10 or IE 11.  Maybe it looks better in the new, webkit powered IE 12?  I haven't test this myself.

    How to use
    You can follow the example code in the app.jsx file on the Github page to see how to use.  The component is called SliderNativeBootstrap. Here’s an example of how you might call it in your ReactJS’s render method:

             min={this.state.min} />

    The value, step, max and min parameters should be self-explanatory. handleChange is the callback method that will be called when the slider actually changes. (NB: this is the onInput event for the native HTML5 control, and the “change” event for the Bootstrap slider.)

    Forcing the Bootstrap version all the time
    An optional parameter is polyfill. When set to true (the default if you leave the parameter out) the component acts as I’ve described it above, i.e. displaying the HTML5 native slider for these browsers that support it properly, and the Bootstrap version for those that don’t. If you want to force the use of the Bootstrap slider for all browsers then you should set this parameter to false, like so:

           min={this.state.min} />

    Is here.
    On load, the slider range is 1,000 to 20,000 with a step of 1,000.
    Click on the Change axes! button, and the slider range changes from 0 to 2,000 with a step of 100

    Update 11/03/2015

    Now available on React Components.