Table of Contents for
React Quickly: Painless web apps with React, JSX, Redux, and GraphQL

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition React Quickly: Painless web apps with React, JSX, Redux, and GraphQL by Azat Mardan Published by Manning Publications, 2017
  1. Cover
  2. React Quickly: Painless web apps with React, JSX, Redux, and GraphQL
  3. Copyright
  4. React Quickly: Painless web apps with React, JSX, Redux, and GraphQL
  5. Brief Table of Contents
  6. Table of Contents
  7. Praise for React Quickly
  8. Foreword
  9. Preface
  10. Acknowledgments
  11. About This Book
  12. About the Author
  13. About the Cover
  14. Part 1. React foundation
  15. Chapter 1. Meeting React
  16. Chapter 2. Baby steps with React
  17. Chapter 3. Introduction to JSX
  18. Chapter 4. Making React interactive with states
  19. Chapter 5. React component lifecycle events
  20. Chapter 6. Handling events in React
  21. Chapter 7. Working with forms in React
  22. Chapter 8. Scaling React components
  23. Chapter 9. Project: Menu component
  24. Chapter 10. Project: Tooltip component
  25. Chapter 11. Project: Timer component
  26. Part 2. React architecture
  27. Chapter 12. The Webpack build tool
  28. Chapter 13. React routing
  29. Chapter 14. Working with data using Redux
  30. Chapter 15. Working with data using GraphQL
  31. Chapter 16. Unit testing React with Jest
  32. Chapter 17. React on Node and Universal JavaScript
  33. Chapter 18. Project: Building a bookstore with React Router
  34. Chapter 19. Project: Checking passwords with Jest
  35. Chapter 20. Project: Implementing autocomplete with Jest, Express, and MongoDB
  36. Appendix A. Installing applications used in this book
  37. Appendix B. React cheatsheet
  38. Appendix C. Express.js cheatsheet
  39. Appendix D. MongoDB and Mongoose cheatsheet
  40. Appendix E. ES6 for success
  41. React Cheatsheet
  42. Index
  43. List of Figures
  44. List of Tables
  45. List of Listings

Appendix A. Installing applications used in this book

In this appendix, you’ll find installation instructions for the following applications (valid as of May 2017):

  • React v15
  • Node.js v6 and npm v3
  • Express v4
  • Twitter Bootstrap v3
  • Browserify
  • MongoDB
  • Babel

Installing React

You can download React in a myriad of ways:

Installing Node.js

If you’re unsure whether you have Node.js and npm, or you don’t know what version you have, run these commands in your Terminal/iTerm/bash/zsh/command line:

$ node -v
$ npm -v

Most of the time, npm comes with Node.js, so follow the instructions for Node.js to install npm. The easiest way to install Node and npm is to go to the website and pick the right architecture for your computer (Windows, macOS, and so on): https://nodejs.org/en/download.

For macOS users who already have Ruby (which typically comes with Mac computers), I highly recommend using Homebrew. That’s what I use, because it allows me to install other developer tools like databases and servers. To get brew on your Mac, run this Ruby code in your terminal (I promise this will be the last time we use Ruby in this book!):

$ ruby -e "$(curl -fsSL
 https://raw.githubusercontent.com/Homebrew/install/master/install)"

Now you should have brew installed; go ahead and update its registry and install Node.js along with npm. The latter comes with Node.js, so as I mentioned earlier, no additional commands are necessary:

$ brew update
$ brew install node

Another great tool that will let you switch between Node versions effortlessly is Node Version Manager (nvm, https://github.com/creationix/nvm):

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh
 | bash
$ nvm install node

That’s it. You should be able to see the versions of Node and npm. If you want to upgrade your npm, use the npm command:

$ npm i -g npm@latest

To upgrade Node, use nvm or a similar tool like nave or n. For example, in nvm this command will also reinstall packages to the new version:

$ nvm install node --reinstall-packages-from=node

If npm gives you permission errors when you install a module/package, then make sure the npm folder has the proper permissions (be sure you understand what this command does before you run it):

$ sudo chown -R $USER /usr/local/{share/man,bin,lib/node,include/node}

Installing Express

Express is a local dependency just like React, meaning each project must install it. The only way to install Express is with npm:

npm i express@4 -S

The -S adds the entry to package.json.

In no way is this is a deep dive into Express.js, but it’ll get you started with the most widely used Node.js web framework. First, install it with npm, like this:

$ npm install express@4.13.3

Typically, you’d create the server file index.js, app.js, or server.js, which you’ll later start with the node command (for example, node index.js). The file has these parts:

  • Imports
  • Configurations
  • Middleware
  • Routes
  • Error handlers
  • Bootup

The imports section is trivial. In it, you require dependencies and instantiate objects. For example, to import the Express.js framework and create an instance, write these lines:

var express = require('express')
var app = express()

In the configurations section, you set configurations with app.set(), where the first argument is a string and the second is a value. For example, to set the template engine to Jade, use the configuration view engine:

app.set('view engine', 'jade')

The next section is for setting up middleware, which is similar to plug-ins. For example, to enable the app to serve static assets, use the static middleware:

app.use(express.static(path.join(__dirname, 'public')))

Most important, you define routes with the app.NAME() pattern. For example, this is the syntax for the GET /rooms endpoint taken from ch20/autocomplete:

  app.get('/rooms', function(req, res, next) {
    req.rooms.find({}, {sort: {_id: -1}}).toArray(function(err, docs){
      if (err) return next(err)
      return res.json(docs)
    })
  })

Error handlers are similar to middleware:

var errorHandler = require('errorhandler')
app.use(errorHandler)

Finally, to start your app, run listen():

http.createServer(app).listen(portNumber, callback)

Of course, there’s more to Express.js than this brief introduction. Otherwise, I wouldn’t have written a 350-page book on the framework (Pro Express.js; Apress, 2014, http://proexpressjs.com)! If you want to hear from a different author(s), then consider Express in Action by Evan M. Hahn (Manning, 2016, www.manning.com/books/express-in-action). The framework is powerful but flexible and can be configured without requiring much magic.

If building Express.js apps isn’t your core competency, or if you know how to do it but need a refresher, check out my Express.js cheatsheet in appendix C or view a graphical version of it at http://reactquickly.co/resources.

Installing Bootstrap

You can get Twitter Bootstrap from the official website: http://getbootstrap.com. This book uses v3.3.5. You have several options:

To link from a CDN, include these tags in your HTML file:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/
 bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src=
  "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
   </script>

For Bower, npm, and Composer, run these terminal commands, respectively, in your project folder (one for each package manager):

$ bower install bootstrap
$ npm install bootstrap
$ composer require twbs/bootstrap

For more information, see http://getbootstrap.com/getting-started.

Installing Browserify

Browserify lets you package npm modules into front-end bundles, ready for use in the browser. Basically, you can turn any npm module (usually only for Node) into a front-end module.

Note

If you’re using Webpack, you won’t need Browserify.

First, install Browserify with npm:

$ npm install -g browserify

As an example, let’s use ch16/jest. Go to that folder, and create a script.js file to include the generate-password.js library. The contents of script.js can be as minimal as this:

var generatePassword = require('generate-password')
console.log(generatePassword())
console.log(generatePassword())

Save script.js, and run this command in your terminal or command prompt:

$ browserify script.js -o bundle.js

Inspect bundle.js, or include it in index.html:

<script src="bundle.js"></script>

Open the index.html file in your browser, and inspect the console; it will show two random passwords. The source code is in ch16/jest.

Installing MongoDB

The easiest way to install MongoDB is to go to www.mongodb.org/downloads#production and choose the appropriate package for your system.

On macOS, you can use brew and run these commands:

$ brew update
$ brew install mongodb

Don’t install mongodb globally with npm. It’s a driver, not a database, so it belongs with other dependencies in the local node_modules folder.

This book uses version 3.0.6, so use later (or older) versions at your own risk. They haven’t been tested to work with the book’s examples.

Most often, you’ll need to create a /data/db folder with the proper permissions. You can do that or pass any other custom folder to the mongod command with --dbpath. For example:

$ mongod --dbpath ./data

Once the database is running (mongod), play with code in the shell, which is mongo:

$ mongo
> 1+1
> use autocomplete
> db.rooms.find()

Here’s an explanation of some of the most commonly used shell commands:

  • > show dbs—Shows databases on the server
  • > use DB_NAME—Selects the database DB_NAME
  • > show collections—Shows collections in the selected database
  • > db.COLLECTION_NAME.find()—Performs a find query on the collection named COLLECTION_NAME to find any items
  • > db.COLLECTION_NAME.find({"_id": ObjectId("549d9a3081d0f07866fdaac6")})—Performs a find query on the collection named COLLECTION_NAME to find the item with ID 549d9a3081d0f07866fdaac6
  • > db.COLLECTION_NAME.find({"email": /gmail/})—Performs a find query on the collection named COLLECTION_NAME to find items with an email property matching /gmail
  • > db.COLLECTION_NAME.update(QUERY_OBJECT, SET_OBJECT)—Performs an update query on the collection named COLLECTION_NAME to update items that match QUERY_OBJECT with SET_OBJECT
  • > db.COLLECTION_NAME.remove(QUERY_OBJECT)—Performs a remove query for items matching the QUERY_OBJECT criteria on the COLLECTION_NAME collection
  • > db.COLLECTION_NAME.insert(OBJECT)—Adds OBJECT to the collection named COLLECTION_NAME

Check out my MongoDB cheatsheet in appendix D, or view a graphical version of it at http://reactquickly.co/resources. In addition to the most-used MongoDB commands, it includes Mongoose (Node.js ODM) methods. Enjoy!

Using Babel to compile JSX and ES6

Babel is mostly for ES6+/ES2015+, but it can also convert JSX to JavaScript. By using Babel for React, you can get extra ES6 features to streamline your development.

ES6 is finalized, but its features—as well as the features of future versions of ECMAScript—may not be fully supported by all browsers. To use cutting-edge new features like ES Next (https://github.com/esnext/esnext) or to use ES6 in older browsers (IE9), get a compiler like Babel (https://babeljs.io). You can run it as a standalone tool or use with your build system.

To use Babel as a standalone CLI tool, first create a new folder. Assuming you have Node.js and npm installed, run this command to create package.json:

$ npm init

Open the package.json file, and add babel lines in JSON. You can place them in any order as long as babel is a top-level property. This tells Babel to use React and JSX to transform the source files. The setting is called a preset. Without it, the Babel CLI won’t do anything:

  "babel": {
  "presets": ["react"]
},

Install both Babel CLI v6.9.0 and React preset v6.5.0 with npm. In your terminal, command prompt, or shell, execute these commands:

$ npm i babel-cli@6.9.0 --save-dev
$ npm i babel-preset-react@6.5.0 --save-dev

You can use this command to check the version:

$ babel --version

There are Babel plug-ins for Grunt, Gulp, and Webpack (http://babeljs.io/docs/setup). Here’s a Gulp example. Install the plug-in:

$ npm install --save-dev gulp-babel

In gulpfile.js, define a build task that compiles src/app.js into the build folder:

var gulp = require('gulp'),
  babel = require('gulp-babel')

gulp.task('build', function () {
  return gulp.src('src/app.js')
    .pipe(babel())
    .pipe(gulp.dest('build'))
})

For more about Webpack and Babel, see chapter 12.

Node.js and ES6

You can compile Node.js files with a build tool or use the standalone Babel module babel-core. Install it as follows:

$ npm install --save-dev babel-core@6

Then, in Node.js, call this function:

require('babel-core').transform(es5Code, options)

Standalone browser Babel

Babel v5.x has a standalone browser file that you can use for in-browser transformation (development only). It was removed in 6.x, but some folks created a babel-standalone module to fill the gap (https://github.com/Daniel15/babel-standalone). You can use that or the older version’s files—for example, from Cloudflare CDN:

Or you can build your own standalone browser file using a build tool like Gulp or Webpack. This way, you can pick only the things you need, such as the React transformer plug-in and ES2015 presets.