Meeting React.js: An Excerpt from ‘React Quickly’

React Quickly Menu

This is an excerpt from React Quickly (Manning, 2016). You can download the entire first chapter for free at Manning. The book is scheduled for release in the first quarter of 2016, but MEAP is available right now. Use code “mardandz” to get 39% off.

Each chapter has a project which is supplemented by a video screencast hosted on YouTube.

React Quickly Screencasts
React Quickly Screencasts

Project: Menu with React.js

The project for this article will be minimal. The idea is to have a dynamically generated menu which will consist of <a> tags.

We’ll use custom React components Menu and Link. They way we create them is similar to the way we create the HelloWorld component in the previous example. The project will show you how to render nested elements programmatically. In the previous examples, we just coded the children manually. We’ll use the map() function for it.

Firstly, you need to get the React file. Let’s use the unminified version for now. The unminified or development version won’t have .min in the name.

The difference is that in unminified version you’ll get helpful warnings along with React code being in the human format in case you want to peek into it. On the other hand, in the minified version the warnings and errors are suppressed, and the code is minified and optimized.

If you haven’t downloaded React already, do so now. Remember that we’re using version 0.14.2. Any other version is not tested with our examples, so use it at your own risk (not recommended).

If you don’t a have Node.js and npm installed, now is a good time to get on board. “But React is a front-end library!” you might say and you’ll be right. React will work just fine without servers and Node.js. For this reason, feel free to skip this step. However, not having Node.js and npm is not recommended because nowadays most web developers I know can’t live without using Node.js for tooling of front-end apps. Node tools have become ubiquitous. Plus, npm has a lot of front-end modules.

So don’t be lazy. If you want to stay on the cutting edge, use Node.js and npm.

I hope it was fun and you’ll be friends with Node.js. Let’s get back to React Menu.

HTML is very basic. It includes the react.js and react-dom.js files which for simplicity are in the same folder as the HTML file. Of course, later on, you’ll want to have your *.js files in some other folder like js or src:

<!DOCTYPE html>
<html>
  <head>
    <script src="react.js"></script>
    <script src="react-dom.js"></script>
  </head>

The body has just two elements. One is a div with ID menu. That’s where our menu will be rendered. Another is a script tag with our React application code:

  <body>
    <div id="menu"></div>
    <script src="script.js"></script>
  </body>
</html>

The script.js is our main application file and it looks like this:

var Menu = React.createClass({...}})
var Link = React.createClass({...})
ReactDOM.render(
  React.createElement(
    Menu,
    null
  ),
  document.getElementById('menu')
)

Basically, we have the main component Menu. To create is, we use React.createClass():

var Menu = React.createClass({

The Menu component will be rendering the individual menu items which are link tags. Before we can render them, let’s define the menu items. The menu items are hard-coded in the menus array like this (you can get them from the model and/or server in a more complex scenario):

  render: function(){
    var menus = [
      'Home',
      'About',
      'Services',
      'Portfolio',
      'Contact us'
    ]

We’ll use a map() function from Array interface to produce four Link components. We don’t forget that the render method must return a single element. For this reason, we have <div> to wrap around our links.

    return React.createElement('div',
      null,

The map() function returns an array where each element is the result of the expression React.createElement(Link, {label: v}) wrapped in <div>:

     menus.map(function(v,i){
        return React.createElement('div',

The <div> has a key attribute which is important. It allows React to optimize rendering of lists by converting them to hashes (access time for hashes is better that for lists/arrays). So basically, we create a bunch of Link components in an array and each one of them takes a prop label with a value from the menus array:

          {key: i},
          React.createElement(Link, {label: v})
        )
      })
    )
}})

In the Link component’s render, we write the expression to create a URL. That URL will be used in the href attribute of the <a> tag. The this.props.label value is passed from the map’s closure in the Menu render function: return React.createElement(Link, {label: v}).

var Link = React.createClass({ 
  render: function () {
    var
      + this.props.label
        .toLowerCase()
        .trim()
        .replace(' ', '-')

Methods toLowerCase(), trim(), and replace() are standard JavaScript string functions. They perform conversion to lower case, trimming of white space on the edges, and replacing of spaces with dashes repressively.

The URL expression will produce the following URLs:

  • home for Home
  • about for About
  • services for Services
  • portfolio for Portfolio
  • contact-us for Contact us

In the render’s return of Link, we pass this.props.label as a third argument to createElement(), and it becomes part of the <a> tag content, i.e., the text of the link.

To separate each link from the other, we add link break tag <br/>. Because component must return only one element, we wrap <a> and <br/> in <div>:

    return React.createElement('div',
      null,

Each argument to the createElement() after the second, for example, 3rd, 4th, 5th, will be used as the content (a.k.a. children). To create the link element, we pass it as the second argument. And to create a break element <br> after each link, we pass the line break element as the fourth argument:

      React.createElement(
        'a',
        {href: url},
        this.props.label
      ),
      React.createElement('br')
      )
  }
})

That’s it. No thrills, but the page should show you five links (or more if you add more items to the menus array). This is way better than copy pasting five <a> elements and then having multiple places to modify the labels and URLs.

For your convenience, I’ll be providing full listings of the files as often as possible. Space is cheap (I hope you’re fan of digital format as I am), and I (as well as 1000s of my readers) find it extremely useful to be able to glance at the entire file at once without having text interrupts or going to Github. If you disagree, simply skip the full listings.

To view the page, simply open it as a file in Chrome, Firefox or Safari (and maybe in Internet Explorer)— Figure 1-X.

var Menu = React.createClass({
  render: function(){
    var menus = ['Home',
      'About',
      'Services',
      'Portfolio',
      'Contact us']
    return React.createElement('div',
      null,
      menus.map(function(v,i){
        return React.createElement('div',
          {key: i},
          React.createElement(Link, {label: v})
        )
      })
    )
}})

var Link = React.createClass({
  render: function () {
    var
      + this.props.label
        .toLowerCase()
        .trim()
        .replace(' ', '-')
    return React.createElement('div',
      null,
      React.createElement(
        'a',
        {href: url},
        this.props.label
      ),
      React.createElement('br')
      )
  }
})

ReactDOM.render(
  React.createElement(
    Menu,
    null
  ),
  document.getElementById('menu')
)

Even for these trivial pages, I like to use a local web server. It makes running code closer to how you’d do it in production. Plus, it allows you to use AJAX/XHR which you can’t use if you’re just opening an HTML file in a browser.

The easiest way to run a local web server is to use node-static, or a similar Node.js tool. To install it, use npm:

$ npm install -g node-static@0.7.6

Once it’s installed, run this command from your project’s root folder to make the file available on the http://localhost:8080 (this is not an external link, run the command below first before clicking the link):

$ static

To stop the server on Mac OS X, simply hit control + c.

The source code for this example is on GitHub and Plunker. To play with the code and/or see the demo online, simply go to Plunker.

 

React Quickly
React Quickly

You can also watch the YouTube videos from React Quickly or buy a book with the 39% discount (code “mardandz“).

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus. http://azat.co http://github.com/azat-co

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.