Learn React.js a Little at a Time, Part 1

Smashing Boxes encourages us to find better ways to deliver high-quality products. One of the ways we do this is learning and trying new technologies. Over the past several months, developers at Smashing Boxes began experimenting with React.js. It's one of those technologies we're excited about. With React, we've found a tool that makes it easy to write code that is simple, testable, and fast.We are seeing a ton of benefits using it. Because React lends itself to being modular, learning and understanding other's code is straightforward. It's already made our code reviews faster. We also expect it to speed up onboarding new developers to the team. Following from that, once we hand the app over to our clients, the system should be easier to pick up and maintain.React code is usually simpler to test than alternatives, too. Testing is huge for us. Anything that increases quality means the client gets a better product, faster.React is an increasingly popular solution for building web app front-ends and we’re really enjoying using it. If you’re comfortable writing JavaScript and eager to start learning about the library, this article is for you.In this tutorial, I will walk through setting up a project on OS X. After it is set up, we will create a Hello World in React. From there I’ll talk about next steps for learning more.

What is React?

React is a library made by Facebook for creating components in JavaScript. Right now, you can use it to build websites and native iOS and Android apps. Two big draws for the library are its performance and its simplicity.It achieves high performance by managing the page with a virtual DOM. What you write describes the structure of the page. When the state changes, React diffs the old with the new and makes the smallest changes needed to get to the new page. Avoiding unnecessary DOM updates is one of the keys to high performing applications.Another benefit of React is that it is much simpler than other popular libraries. This is because React is only the view layer. You can use it without bringing in an entire framework. In fact, many pair React with full-fledged frameworks like Angular, Ember, and Backbone.

Getting Everything Installed

If you are developing on a Mac, using Homebrew makes installing and managing your tools easy. I am going to assume you have it installed, but if you don’t, consider following the instructions in the link above. To get started, I suggest getting Node Version Manager.$ brew install nvmWith that installed, go ahead and install the current stable version of Node.js.$ nvm install stableWe will be using Webpack, a popular choice for React projects. Below I’ll detail why we use it. For the moment, let’s install it and its dev server with the following command.$ npm install webpack webpack-dev-server --save-devAlso, we'll install it globally so we have easy access to its command line tools.$ npm install -g webpack webpack-dev-serverNow let’s create our project!$ mkdir hello-world$ cd hello-worldAnd initialize a new project here:$ npm initEnter the data needed to start the project, and then add the React dependency with this:$ npm install react react-dom --saveWe now need to configure Webpack. In the project’s root folder, create a file named webpack.config.js and set it to the following:module.exports = {
entry: {
app: ['./app/main.js']
},
output: {
path: './app',
filename: 'bundle.js'
}
};
This will configure Webpack to build our client files starting with app/main.js. Webpack will crawl all dependencies we require and compile it into one file. This file is app/bundle.js, which we will include in our HTML.There! That is all we need to get the project set up, and we are ready to begin writing some code for it. Not as easy to set up as say a Rails project, but not too bad either.

Why We Use Webpack

Webpack is a module loader. Unlike most other languages, JavaScript does not include one. This has led to many independent projects designed to solve this problem. Webpack is similar to libraries like Browserify or Require.js, but it can actually do much more. It ends up replacing a good bit of what you would do in Gulp or Grunt — popular tools used primarily for writing build tasks. With it we can use AMD, CommonJS, or even ES2015 style modules. To showcase the differences between them:

AMD

require(['react'], function (React) {});

CommonJS

var React = require('react');

ES2015

import React from 'react';
In our code we are using the CommonJS style, originally popularized by Node.js.

Implementing Hello World

Within our project, let’s create the app/ folder. It will be where we write our code.$ mkdir appNow add a file at app/index.html. Let’s put the following code in it:<!doctype html>

Hello World
<div id="react-mount"></div>
<script src="bundle.js"></script>

Here you see the bundle.js file mentioned above. We also have an element with an id of react-mount which we will use as the root of the app. Anything within this div is managed by React. Because of that, do not modify any of the descendant elements outside of your components!The final file we will add is app/main.js which will have our HelloWorld React component.var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = React.createClass({ render: function () {
return React.createElement('div', null, 'Hello World');
}});

ReactDOM.render(React.createElement(HelloWorld), document.querySelector('#react-mount'));
Here we are using the CommonJS module loading style provided by Webpack to pull in React. We define a new component with React.createClass named HelloWorld. It has a render function and in it we create a new div with no attributes and with the text “Hello World” within it. It will look like this (React adds an attribute to help maintain references to nodes, but it is safe for our purpose to ignore it):<div>Hello World</div>
The first argument to React.createElement can be a string for any HTML element (div, span, header, footer, etc.). The second argument is an object of attributes for this element. For example, we would do the following if we wanted to create a link to where I work, Smashing Boxes.React.createElement('a', { href: 'http://smashingboxes.com' }, 'Smashing Boxes');
//<a href="http://smashingboxes.com">Smashing Boxes</a>

It is worth noting that you can use any regular HTML attribute here except for two special cases: for and class. These are reserved words in JavaScript, so the React authors chose to provide htmlFor and className as the keys for those attributes.The third argument and all arguments after it are children of the element we are creating. These can be other elements made with React.createElement or strings. Check out what it might look like if we converted some markup from a Bootstrap example to using React elements.React.createElement('div', { className: 'form-group' },
React.createElement('label', { htmlFor: 'exampleInputEmail1' }, 'Email address'), React.createElement('input', { type: 'email', className: 'form-control', id: 'exampleInputEmail1', placeholder: 'Email' }));
//
<div class="form-group">// <label for="exampleInputEmail1">Email address</label></div>
// <input id="exampleInputEmail1" class="form-control" type="email" placeholder="Email">
//

render is the first component lifecycle method we’ve come across. Every component must have one, and it’s fairly common for that to be the only lifecycle method a component needs. React calls it to create the virtual DOM element, and later adds the result to the page.On the last line of the file is where we render this component to the element with id react-mount. Notice we use React.createElement again. This time instead of using a string, we use the class we defined above.We’ve completed Hello World in React! Very simple, and nothing else is required. Just start up the server using$ webpack-dev-server --content-base app/and open http://localhost:8080/ in your favorite browser.

Next Steps

After doing this, you now know how to bootstrap a React project and create simple components. You can find the full code here: https://github.com/zachary-kuhn/hello-world.Up next in this series we will talk about more parts of the component lifecycle and how to create more complex components as we build out a small app. These advanced components will take user input and maintain state.We will also upgrade the project to using ES2015. Many people start new projects using it, so we will adopt it as well. There will be other upgrades we make to the build system that help keep our workflow nice and smooth, too.Finally, we will convert this to using JSX. JSX is a version of JavaScript that allows XML within the code. Next time we’ll see it in action and I think you’ll agree that it makes the code a bit more readable.Thank you for reading, hope you’ve benefited from this and I look forward to delivering these next parts soon.Update 11/4/2015: Update code examples to use React 0.14.

Learn React Series

       
  1. Part 1: Introduction to React.js
  2.    
  3. Part 2: ES2015 and JSX; Intermediate components with props and state
  4.    
  5. Part 3: Flux architecture and Immutable.js

Want to learn why I think React has a bright future? Check out our article comparing React against Angular and Ember.--Need extra muscle on your next React.JS project? GET IN TOUCH.

Subscribe to the Smashing Boxes Blog today!

Smashing Boxes is a creative technology lab that partners with clients, taking an integrated approach to solving complex business problems. We fuse strategy, design, and engineering with a steady dose of entrepreneurial acumen and just the right amount of disruptive zeal. Simply put, no matter what we do, we strive to do it boldly. Let's talk today!

Related Posts

The Shifting Landscape of Seed-Stage Startups: Insights from Carta

The seed-stage startup landscape is evolving, with shifts in deal volume and geographic distribution. The data provided by Carta offers valuable insights into these changes.

view post

Why Everyone Needs a Lab

Now through July 18th, you can see a digital art installation in the first-floor window of the 21c Hotel

view post