First React Component

In my last post, I showed how to set up the React environment — npm to download packages and their dependencies, webpack to minify and bundle code into one file for production, and Babel, a compiler that processes React into JavaScript the browser can understand.

I left off with using regular JavaScript to select an element and set its inner HTML to “Hello World!”. In this post we’ll use a React component to do that.

Writing a React component is so much easier than setting up the React environment, because React is really just JavaScript. If you are comfortable with JS, it follows that you’ll be at ease with React.

In index.js, set two variables equal to the two React modules we downloaded in my last post, react and react-dom. The syntax for loading a module is require(insert-module-name).

On line 4, we’ll define our first React component and set it to a new variable, HelloWorld. We’ll start without using ES6, in which case you can use the createClass helper to initialize a component class. Every React component includes a render function that returns the HTML you want to display in the DOM.

On line 12, we use the render method from the the ReactDOM module to update the DOM with the output from our HelloWorld component/function. We pass it the component first, the selected element last.

Next run npm run start to start the development server, visit http://localhost:8080/ and you’ll see “Hello World!” displayed.

It’s always worth using a web inspector to see what’s being rendered in the DOM.


As expected, the HelloWorld component has rendered inside the app. Note how the div element we rendered was automatically assigned a data-reactroot attribute. This allows tools like react-detector to identify a React app without any hiccups.

In my next post, I’ll demonstrate how functional components and props are used to organize your UI into reusable, isolated building blocks. All react components are pure; they always return the same result given the same arguments and never change the state of variables outside of their scope (no side effects!). This makes React components easy to test.


React Environment: NPM + Webpack + Babel

Building a React component is easy. It’s setting up the environment that’s tricky — you’ll need npm, webpack and Babel to get started. Once set up, webpack will take all your files, compile them into JavaScript the browser can understand, and output them to one single file.

To start a new React project, create a new directory call webpack-test-project and cd into it. Run npm init. This will create a package.json file in the root of your project.

Next run npm install –save react react-dom. This will create a new folder in the root of your project call npm_modules and will download the react and react-dom modules to it, along with any of their dependencies. As well, package.json will be populated with a dependencies object that includes any downloaded modules. This is great because instead of pushing all your modules to GitHub, a teammate can clone your project, run npm install, and presto, react and react-dom will be downloaded to their npm_modules folder.

Next, you need to install webpack via npm. webpack is module bundler. It will take our assets and transpile them according to the specifications in our config file. In this case, we’ll be configuring webpack to use babel and babel-preset-react to compile our code. By compile, I mean that webpack will process our React code to modern javascript that the browser can understand. Babel can also process ES6 & ES7 to JavaScript the browser can understand.

To install webpack and Babel run npm install –save-dev html-webpack-plugin webpack webpack-dev-server babel-{core,loader} babel-preset-react. Notice that this time we used –save-dev because we will only be using these packages in development mode. All of these packages will now be listed in package.json:

Next run mkdir app && cd app and create an index.js and index.html file. Then, in the root of the project create webpack.config.js — we’ll use this file to configure webpack.

We configure webpack by building an exports object, with three important keys: entry, output, and module. Entry tells webpack which files to process; Output tells webpack to bundle your JS files into one new file called index_bundle.js that lives in a new folder /dist in the root of our project. Module tells webpack which loaders (processors) to use to compile our React code into JavaScript the browser can understand.

The Module object contains an array of loaders. In this case we only need one loader, babel-loader, to process our code. In the loaders array we tell webpack to take any file that ends in .js (except those in the node_modules folder) and process them with babel-loader.

But we aren’t finished yet, Babel has its on config file. Create a .babelrc file in the root of your project that tells Babel which presets/processors to run on your code, in this case react.

Ok, almost finished with configuration. The only outstanding issue is instruct webpack to create a new index.html file in the /dist folder and link to the bundled script, index_bundle.js. We will use the HTML webpack plugin to accomplish this task. Run npm install –save-dev html-webpack-plugin. This will update your dependencies in package.json and download the plugin to node_modules. Next, we initialize the plugin in webpack.config.js.

First, declare a new variable and set it to the HTML webpack plugin module. The object we pass to HtmlWebpackPlugin on initialization contains three properties: template, filename and inject. Template points to the file we would like to transform, filename specifies the name of our output, and inject specifies where in the output we want webpack to put the link to the bundled file, in this case the body tag. Then, at the end of the exports object, add a new property plugins and set it to our plugin instance, HtmlWebpackPluginConfig.

Phew, now all the architecture is in place but we still need to define scripts to run webpack. We’ll use two scripts, one for production, webpack -p, and one for development, webpack-dev-server, and put them in package.json. We’ve named our scripts production and start.

Scripts allow us to define shortcuts for common administrative tasks like bundling code. To bundle and compile our code for production as configured in webpack.config.js, run npm run production. After, you should have a new folder in your root project, /dist, with a new index.html file linking to a single compiled file, index_bundle.js, with all of our JavaScripts ready for the browser. You’re file structure should look like this after running the command.


Finally, let’s test this all out with some code. In index.html  create a div element with an id set to app.

And in index.js, fetch the app element and set its inner HTML to “Hello World!”.

Run npm run production one more time. Now when you open ./dist/index.html you should see Hello World! in the top left of your window, which means npm, webpack and Babel are all working properly!

And check out your dist/index.html file. It should be exactly the same except it will link to index_bundle.js in the body.

index_bundle.js will contain a minified version of index.js, transpiled to browser-friendly JS.

Finally, because we aren’t in production mode most of the time, it makes more sense to only compile our code when pushing to production. While in development mode, take advantage of the start script we defined about in package.json. Run npm run start and you can view your progress at http://localhost:8080.

Setting up the environment for React is a bit complicated but it gets easier with practice. I recommend building the environment a few times. In my next post, I will show how to build a React component to display “Hello World!”.

For further information on setting up the React environment, check out this amazing free tutorial which informed much of this post.





Learning React: The Environment – NPM scripts

I’m excited to be learning a second front-end framework, React, because I like the idea of writing ES6 JavaScript components with embedded HTML instead of embedding HTML in JavaScript, like with Angular 1.

A prerequisite to learning React is having a basic understanding of its environment, which includes npm, the package manager for JavaScript. npm allows you to easily install and update modules like jQuery.

To initialize an npm project, run npm init from the console. This will generate a package.json file in the root folder of your project.

To install a package like jQuery, run npm install jquery –save. This creates a new folder called ‘node_modules’ in your project and downloads the jQuery package to it.

The –save part of the command will include jquery under dependencies in package.json. This is nifty because when a colleague clones your project, they can simply run npm install and any dependencies in package.json will be downloaded to their node_modules folder.

Another cool feature of npm is scripts. Scripts allow you to store commands that would otherwise be cumbersome to type out in the console. For example,  instead of always typing karma start –singleRun to run your Karma tests, you can define a script like…

… and now you just have to type npm test to run your specs. This comes in handy as a project grows and files get deeply nested, as you deploy and have to manage ever more command line tasks.

When I first learned about npm scripts, I found it helpful to compare them with Rake tasks in Rails. Although Rake tasks are more substantive and involve functional code snippets, like npm scripts, they allow you to define administrative tasks and run them from the command line by their definition. Here’s a fallback Rake task I wrote to upload files to Amazon S3 that are older than 300 seconds:

To execute this task you would run rake:upload_jobs from Rails console, or use a scheduler to automate it every few hours.

Next I’ll be learning about the module bundler webpack and building my first React component!


Hooray for ES6 modules on Rails Part 2: Testing

In my last post, I integrated modern JS into a Rails app with Browserify via Browserify-Rails gem, and getting started with writing specs in ES6 is just as easy.

1.) Set up Browserify-Rails via my last post

2.) Add teaspoon-jasmine gem to your gemfile

3.) Make sure Browserify is configured to load spec files

4.) Run “bundle install” from Rails console

5.) Run “bundle exec rails g teaspoon:install” from Rails console

6.) Import whatever class you are testing and use ES6 syntax!

7.) Run your specs in the browser at http://localhost:3000/teaspoon, or in the console via rake teaspoon


Hooray for ES6 modules on Rails Part 1: Getting Started

In my most recent project, I implemented Conway’s Game of Life using ES6 modules + Rails. With the help of Browserify via Browserify Rails, I was able to organize my code with node-flavored modules and compile them with Babelify for use in the browser.

It’s the first app I’ve built using modern javascript, and doing so was rewarding and a good primer for using ES6 with front-end frameworks like React moving forward (I did not use a front-end framework in this project).

Getting started with Browserify via Browserify Rails is super easy. If you don’t already have node installed, you can do so via Homebrew. Once node is installed, follow these directions to get up and running with ES6:

1.) Add “gem browserify-rails” to your gemfile

2.) Run “bundle install” from Rails console

3.) In application.rb, config Browserify to use Babelify to compile ES6

3.) Run “npm init” from Rails console to create a package.json file in Rails root. Add the following dependencies:

4.) Run “npm install browserify browserifyincremental babelify babelpresetes2015 save” from Rails console to install the required packages locally

5.) Start writing ES6 classes and export them for use in other classes (via import).

Example of exported Cell class:

Example of importing Cell class and using its initialize method in World class:

6.) Require all classes/modules in application.js

That’s it. You’re now ready to use modern JS in the browser and feel confident that you are current with the ever-changing JavaScript landscape.

Postscript: If you haven’t built Conway’s Game of Life before, I highly recommend getting started with this fantastic test-driven tutorial. And definitely solve the problems on your own when he gives you a challenge; you will learn a ton more that way and feel good about it. Note that this is a ruby tutorial and the game is displayed via the Gosu gem in the console. The ES6 stuff above is only applicable if you build the game in the browser.