Learning React

Learning React is hard.

On one hand the code looks like HTML.  But it’s not straight HTML, it’s got other code decorators injected into it. As a result the browswer can’t read the files as it can read straight (vanilla) javascript.

An intermediate compiler/transpiler is needed to convert JSX (the HTML looking javascript) into JS that the browser can render.  This is what Babel is used for.

The first few times I tried to teach myself React, I got really hung up on JSX. I had a hard time keeping straight what it was used for, and it’s appearance being so similar to HTML kept confusing me. In reality it’s not HTML with some javascript thrown in, it’s JavaScript with HTML tags thrown right in.

In normal JavaScript you would have to encapsulate any HTML you wanted to send to the Document/Browser Window in string tags, which starts to look pretty messy. JSX allows you to not only write straight HTML markup in your JavaScript, but also create your own HTML tags, called Components via the React library. Now that I understand it’s purpose, it makes a whole lot more sense. If it’s confusing to you, stick with it.

Basic Starting Code

To start working with React, simply include two javascript libraries, one for React itself and one for ReactDOM to render what we are creating onto the browser window (the DOM).

You’ll need to include either a 3rd javascript library, or work with your tooling scripts to allow Babel to transpile your React code (JSX) into vanilla JS.

You can use these files locally by downloading them from here: https://facebook.github.io/react/docs/installation.html

<!DOCTYPE html>
    <title>Learning React</title>
    <script src="./js/react.min.js"></script>
    <script src="./js/react-dom.min.js"></script>
    <script src="../../js/browser.min.js"></script>


Don’t Let the Tooling Derail you

It can take time to wrap your head around the tooling options that are available.  What is “tooling?” Tooling is the set up of your local system to automatically compile your code, compact your JSX into vanilla JS to be use by your local or remote file server, a “linter” that will automatically check your syntax as you go, and so forth.

When set up correctly the right tooling can make your job very easy, but until you understand the purpose and function of each piece of tooling, it feels like a lot of extra code just to write some javascript.   Since javascript is supposed to be the language of the web, setting up a local React dev environment with the right tooling feels like a big step back in time.

But … they tell me it will be worth it!

Basic React Building Blocks

“Hello World”

Hello World is the traditional first step in learning any new coding language or framework. What’s the simplest way to get text on the screen.  In react it is a two step process. The first step is to simply create a “target” for your text by creating a single div with a name in your index.html file.


<div id="app"></div>


Next you tell ReactDOM to display “Hello World” to that target. If you’re writing this as a single file, simply create a script tag and mark it up as text/babel like this:


This is why we included the 3rd Javascript file above, so that the text/babel script will be correctly transpiled into javascript.

Now we “render” some text to our target using code that appears similar to HTML…but it’s actually JSX. The library used to render the JSX is ReactDOM, our 2nd included library above. We haven’t actually written any React yet, this is just the set up so that our React code has a way to be rendered and a target to go to. The render method takes two paramenters. The first one is basic HTML, and the 2nd is the target, which we’ve already created before.



Hello World!

, document.getElementById('app'))

Now if you open this index file in a local browser, assuming you’ve got proper script paths to react, reactDOM and babel, you should see your Hello, World! text on the page.

(A nice html server is


, that you can install with npm).

Here is the full index.html file up to this point:

<!DOCTYPE html>
    <title>Learning React</title>
    <script src="./js/react.min.js"></script>
    <script src="./js/react-dom.min.js"></script>
    <script src="../../js/browser.min.js"></script>
</body> </html>

Node.js: Redirecting to new page after an XML Delete request

I couldn’t think of a clearer way to title this post, other than describing the action I was trying to accomplish.  It took me 4 days to sort this out from hints I received online (Free Code Camp Gitter Help channel), the MDN Javascript documentation and a host of Stack Overflow questions.

The project I am working on is the Free Code Camp Voting App project. it’s the first of the full-stack apps, I used MEEN (Mongo ,Express,  EJS (or your choice of binding script), Node).

I first attempted this app 18 months ago, and failed miserably. Normally failure is an opportunity for learning, but it was so painfully challenging at that point because I barely grasped each component of the stack and getting them to work together was incredibly confusing for me.   I even used Yoeman, which SHOULD make it easier…but in reality it just made it more confusing for me. I was not ready to use that framework since I had a very thin grasp of how all the parts connected to each other.

Prior to this my only experience with full-stack was using Rails.   Some familiarity (but far from expertise) with Rails gave me a perspective of what I could / should be doing in terms of modularizing my application code.   JavaScript, however, allows you to make those decisions on your own about how you would like to configure your folders, scripts, public assets, routes, etc.

I ended up with what i felt was a reasonable blend of decent modularization, but also chunks of code contained in one file so that I was able to keep the parts straight. Perhaps future projects I’ll feel more comfortable making things more modular.

So here is the basic folder structure I opted for in my applicatoin. I’m NOT suggesting you do it the same way…this is simply how I ended up doing it and it’s working OK for right now. I’m sure i’ll make modifications , or possibly go back to yoeman, clementine.js or maybe try Sails.js for my next app.

--poll.js  (this was catch all JS for the app..>I ended up not using it at all)
-bower_components  (front end scripts stored locally)
-config  (files for authorization & authentication using passport)
-models (models for mongoose/mongo collections)
--index.js  (ties the other two in)
--poll.js  (poll model)
--user.js  (user model)
---chartPoll.js (again I ended up not using this, instead used embedded script tags)
-routes  (self explanatory)
--pages (ejs templates)
--partials  (ejs partials for nav bar, header, footer, etc)
todo.txt (used webstorm's "TODO:" syntax to track bugs and todo items)

I started the project by working from the Scotch.io tutorial, Node Authentication with Passport.   I had done that tutorial once in the past, and it went well, so I rushed through it more quickly than I should have this time to get something propped up real quickly that i could use.  But once i got it working, I ignored the user sessions until after I had the voting routes & controller code working well.  That served me well, because once the app was mostly functioning I could then concentrate on allowing actions only for authorized users depending on the route (posting a new poll should only be allowed for authorized users for example)

The next task I tackled was using mongoose for the first time in an app, that is, not a tutorial.  This was not as difficult as I imaged it would be and I think in time it will be easier in the long run.  I think one of the big advantages is transparency of making the connection and closing the database…all that is done for you with Mongoose.  I’m still not fully aware of what other steps it saves, since straight vanilla node.js driver mongo is not really all that challenging (minus callback hell).

At this point I needed to get some data into my database (using mLab, but could easily use local installation of mongod), and I didn’t want to fuss with the front end.  In all the mongo documentation, they provide a small database collection creation script that you run prior to running the commands.  


This post is a draft I started a few months ago and can’t readily recall all the details I wanted to include. However there is some good reminders in here and hopefully they will help some others, so I am publishing it anyway

Free Code Camp’s Front End Certificate

I’ve been involved with Free Code Camp from nearly the beginning. I stumbled across an article by Quincy Larsen about how difficult it is teaching yourself to code. The thing that stood out to me was that he acknowledged how much time can be wasted, and progress stunted, but jumping from one tutorial to the next or one language to another without really learning the things you need to learn to becoming a well versed coder.

I have been a programmer since the age of 12 when I first entered some game contests programming in Basic using an Apple ][e computer.  We didn’t own a computer then, save for some ancient IBM thing that ran lotus   1-2-3 on a flip down keyboard and a monitor that looked like an old oscilloscope.

Yet I still struggled getting up to date  on current web technologies for interactive applications with the end user.


Before med school I worked for a year as a “database systems analyst” which was a fancy title for what I actually did.  I programmed hand-held bar code scanners for custom applications that worked with our company’s larger Computerized Maintenance Management System.   I had to learn a new coding interface for these devices, and had to know our own code well enough to integrate these cool little tools with the system software.


When I held a meeting for our sales staff to update them on the handheld scanners (about the size of shoebox for a pair of baby shoes), I passed out name tags in bar code.  They had to scan them to find their own name tag in order to learn how the devices worked.  It was really a lot of fun and I’m thankful I had mentors who taught me so much about programming interfaces, user interaction, database programming and design and more.


But it also poisoned me…I have enough knowledge of how the back end works that any time I have an idea for an application or interface, I know just how I’d like to implement it… in 1997 technology.


But catching up to web 2.0 and beyond has been a years long pursuit.


All this while still working as an ER physician and a triathlon coach means I do it in fits and starts.  Free Code Camp tracks my progress for me which is also a huge asset of the website.  And it’s free!


Check it out if you want to learn or improve your javascript!

Learning D3 – essential skills for the Javascript Programmer

Learning D3 – essential skills for the Javascript Programmer

Recently I’ve been experimenting with and trying to learn the D3.js library in order to create ziplines and develop some relative expertise at Free Code Camp. D3 stands for Data Driven Documents. As a former cartographer and information graphic artist in the 90s, discovering the possibilities with D3 for browser based interactive applications is like Geraldo Rivera discovering Al Capone’s vault! (except he didn’t…)

While it’s seemingly straightforward for those who have climbed the learning curve, “getting it” takes some experimentation, practice and intuition. Several reasonable tutorials exist for learning the library but its fair to say that whether one speaks to you at this moment depends on your prior javascript experience.

My first attempt at creating a bar chart with D3 was held up mostly be json data extraction and a standard array…pretty basic data manipulation as far as javascript goes, but because all the existing D3 tutorials I found had explicitly named key:value pairs, it took me two days to figure out that d.name and d.value as used in the examples were the same thing as d[0] and d[1] in my simple nested array structure that did not have named keys.

Small setbacks like that can be extremely frustrating, but it does seem it’s part of the learning experience.

So here is my short, and growing list of fundamental D3 tasks that should help you learn to not just follow or copy a tutorial, but start to manipulate the DOM and your data to create the visualizatoins you want.

My personal goal is an understanding of D3 that is good enough to not have the coding “get in the way” of creating the visualization I want.

Basic D3 skills

1. Know how to import the library into your JS project

    <script src="http://d3js.org/d3.v3.min.js"></script>

2. Manipulate the HTML DOM elements, similar to JQuery


<div class="infobox">
<p>Here is where we will say something.</p>


d3.select(".infobox").style("display", "block");	
d3.select("p").text("This bar has a value of " + rect.attr("height") + " units.");

3. Create a simple data array of one dimensional elements to use in your test code


for( var i = 0; i < 25; i++ ) {
	data[i] = Math.floor(Math.random()*100);

4. Using SelectAll, create a new set of rectangles or circles (try both)!


5. Give them a fill color, width, height & x,y position (for rectangles) or fill, x, y center and radius (for circles) and display them on the canvas. (added to snippet from #4)

.attr("x", function(d, i) {
 return i * 21; })//Bar width of 20 plus 1 for padding
 .attr("y",0 )
 .attr("width", 20)
 .attr("height", function(d) {
 return d; }) //Bar width of 20 plus 1 for padding

Steps 4 & 5 above constitute the very common “selectAll + data + enter + append” sequence that will allow you to generate some self-sufficiency at creating simple D3 documents. When you can do this for a new set of data within a few minutes, that is, you’re no longer debugging the code, and simple looking up reference material and writing from scratch, start keeping an eye open for interesting APIs or data sets that you can create new data sets from.

You can begin to dress them up by implementing best practices for information graphics including a proper scale & labels for your axes, a title, and margins or padding so the chart can “breath”.

GDP Bar Chart with D3

Screen Shot 2015-05-05 at 1.15.14 PM

While this isn’t a tutorial, I hope that this list of basic D3 skills and snippets helps you get oriented to the larger task of creating your “dream charts” with complex data.

Please leave a comment or link to any examples or codepens or gists you’ve created.

The JavaScript Event loop for Emergency Physicians

If you’re a reader of my blog past or present you’ll know that I’ve long been interested in programming and am also an Emergency Medicine physician.  While studying javacript callback functions I was referred to this talk which explains them well, but it didn’t really “click” until I saw the visual “event loop” waiting for it’s opportunity to let the main stack know there were results to dealt with from prior callback functions.

What’s a callback function? This is one I’m still wrapping my head around, but it allows for a task to be worked on while the main program continues to function.  This way the main program is not held up waiting for results that may be dependent on some 3rd party, such as downloading a file or communicating with an API, or any other calculation or processing that needs to be done.

A callback function seemed confusing to me because I was trying to understand the literal terms of what was being “called back”.  While I’m still not certain I get that, let me explain it in terms of how the emergency room functions.  If you’ve ever been a patient in the ER or in a hospital and had a health care worker stop into your room to keep you updated on results or what exactly you’re waiting for, this should make a lot of sense to you.

And if you happen to also be an Emergency Physician or Practitioner managing complex care for many patients, you’ll also recognize YOUR role in the “event loop”.

The physician’s physical location is the main stack

In order to diagnose & treat a patient. The physician has a role in evaluating the patient’s primary complaint, including a history, a physical exam, objective testing data, and then a clinical summary of what it all means.

Some of this can only be done by the physician being present, in the room, talking with the patient and doing a hands on physical exam. The physican may be caring for many patients at once, but can only be in one place at a time. The physician’s physical location combined with what stage of evaluation they are in is kind of like the main call stack.

  • Pick up a New Chart
  • Read the chief complaint, note allergies, prior medical issues, and nursing notes that may be pertinent
  • Go to the patient room and talk with the patient, get further history
  • Perform a physical exam on the patient
  • Return to the desk or order entry area and order appropriate blood tests, x rays, other diagnostic tests, or place a phone call to a specialist.

All of these things ideally happen in an uninterrupted sequence. Bear with me here, interruptions are common, but the above set allows for full focus on ONE patient at a time and minimizes early errors in thinking, or forgetting something like an out of the ordinary lab test for your patient that seems appropriate (for example, a TSH is not a routine test, but in some cases it may be valuable to the ER physician).

So the call stack, the main flow of the ER, involves the physician reviewing charts, seeing patients and ordering tests. She does this twenty times a day, but must find time inbetween these “stacks” to review all that data she’s ordered.

Each test ordered is a callback function

When the physician or practitioner orders blood tests, several things happen automatically that creates a new work routine for one or more people. Stickers are printed for the blood tubes, a technician sees the order and grabs the supplies to draw the blood. The technician or nurse physically goes to the room to draw blood on the patient. Blood tubes are labeled and sent to the lab with care.

The lab receives them and begins processing them and eventually results are returned, either on a printer, via telephone or most often, in a computerized record system. The lab runs the blood tests on several different machines and they results come back at different times, to be reviewed by the nurse & physician when they are available to synthesize that information and make a decision on it.

Clearly if the physician had to wait for all of this to happen, or even part of it, before moving to the next patient, the flow of the ER would creep to a complete halt. Physicians would be limited to 1 to 3 patients per day rather than 2 to 3 per hour. Only because these ancillary tests are “callbacks” can the physician move on to the next patient in the queue to being their evaluation.

The event loop allows the physician to process the results
At some point the physician has a brief mental & physical break beteween seeing two patients, or between a phone call and the next patient and can turn to the computer to see what’s resulted on a waiting patient. This is analgous to the call stack (the physicians workload) finally being open again to pay attention to a new piece of information.

The results of the testing (the callbacks) are available to review

An experienced physician understands the flow of effort 7 energy between picking up a new chart (filling the call stack again) and reviewing prior results on older patients ( the call backs) This is the “event loop”. The event loop waits until the call stack is empty, until the main program flow has returned from other tasks, and can manage the results of functions, whether it is a set of calculations, a file, or information from a web site.

The event loop analogy applies to not only test results but any other type of interruption to the physicians call stack. Interruptions create a mistake prone environment, so it’s vital that both physician and other staff recognize the ideal moments in which to have new information processed.

Asynchronous Patient Flow

Only because of the asynchronous nature of the “Physician Stack”, “Callback Testing”, and “Event Loop Interruptions” can today’s healthcare environment support the massive volume of patients needing to be seen. We are always looking for ways to become more efficient while maintaining good patient care, satisfaction, reducing mistakes or injuries, and maintaining work satisfaction for all involved.

I would imagine in the same way during my exploration as a javascript full stack developer, I’ll continue to seek out ways to maintain efficiency, improve program flow and keep myself happy along the way while getting a good product for any client I work with.


Loupe: A visualization of the JS CallStack/Callback/Event Loop

Free Code Camp – A Full stack JavaScript development education platform

Converting a Javascript object to a readable JSON file

While working through the final challenges at FCC (Free Code Camp) I coded a live working Angular.js project alongside the hand-holding tutorials that are entirely done in side the browser.

The tutorials at CodeSchool are excellent as they prompt you step by step through what initially seem like very complex tasks.  As a I worked through the tutorial and watched the videos, I recreated the project (a fun little gemstore) on my own computer.

This was really important to me to convince myself that I understood the technology.

However in the final final step of the angular.js course, and thus the final challenge of Free Code Camp, they introduced a cool trick to import data from an external file in a format called JSON.  JSON is very similar in appearance to how a Javascript object appears…it’s human readable in the same way, however the syntax is slightly different.


It was going to be a daunting task to convert the entire object from Javascript to JSON just to get this last step working.  A little googling led me to two pieces of advice that solved my problem instantly.


First was this gem at Stackoverflow:

  1. Launch Firefox/Chrome/Safari
  2. Open Firebug/developer tools
  3. Copy/paste your code into the console.
  4. Then type console.log(JSON.stringify(object)) and voila!

So I tried it, and got back a minified version of the JSON object. This actually worked fine, but I couldn’t read it, so I used this nifty site to simply format it with line breaks and tabs:


Just click the icon of the little outline after pasting in the results from your console and presto…there is your JSON file.