TL;DR: The JavaScript ecosystem has a plethora of libraries and frameworks for front-end development. ReactJS is one of the young and shiny new libraries on the block. Even though it's only a few years old, it has gained lots of traction from JavaScript developers around the world. One of ReactJS's selling points is the ability to easily build reusable components. Another salient point is that not only does it perform on the client side, it can also be rendered on the server side.


Why React?

ReactJS was built by Facebook to solve one problem: building large applications with data that changes over time. It utilizes the concept of the Virtual DOM that selectively renders subtrees of nodes based upon state changes. The component based architecture that ReactJs emulates makes it incredible to work with. Components in ReactJS are self-contained views that get their data from triggered events or as inherited property from other components. There are essentially two main ways of writing components, using React.createClass and extending React.Component. Props and States in ReactJs also makes it fun to work with. Learn more about the basic concepts of React here.

Using React.createClass Syntax

var HelloComponent = React.createClass({
  render: function() {
    return (
      <div className="hello">
        Hello, world!
      </div>
    );
  }
});

ES6 Way

class HelloComponent extends React.Component {
  render() {
    return (
      <div className="hello">
        Hello, world!
      </div>
    );
  }
}

ReactJS supports the use of ECMAScript 6 features. With Babel, you can write ReactJS the ES6 way, making use of classes, arrow functions and a host of other ES6 features.


// CommonJS way
var React = require('react');
var ReactDOM = require('react-dom');

// ES6 Way
Import React from 'react';
Import ReactDom from 'react-dom';

// ES5 way
var Main = React.createClass({
  render: function() {
    return (
      <div>
        Hello there!
      </div>
    );
  }
});

// ES6 way
export default class Main extends React.Component {
  render() {
    return (
      <div>
        Howdy!
      </div>
    );
  }
}

Let's Get Started

Bootstrapping a ReactJS project involves setting up lots of tools, and it can really be a daunting task. Thankfully there are several tools provided for developers by the community to aid in setting up your project without breaking a sweat. In this post, we'll cover tools that you should be aware of in bootstrapping your next ReactJS project.

Building a React App

The first step is to set up a development environment for your ReactJS project. Webpack, a bundler utility and Babel are key tools here. Babel lets us write code that uses new ES6 features, and then transpiles that code into standard ES5 code that can actually run in the browser. When setting up a new project:

  • I assume Node.js and NPM is installed, run this command: npm init to create a package.json file
  • Run this command in your terminal: npm install react react-dom babel-core babel-loader babel-preset-es2015 babel-preset-react webpack webpack-dev-server --save
  • Create a webpack.config.js file. This file handles bundling all our assets, converting JSX to JS files and launching the development server. Bundling refers to combining, compiling and minimizing multiple files into just one file to be served to the client.

Note: JSX is a JavaScript syntax extension that looks similar to XML. You can write concise HTML/XML-like structures in the same file as you write JavaScript code. With Babel, JSX files can be transpiled into actual javascript code.

A sample webpack.config.js is shown below:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/App.js",
  devServer: {
    inline: true,
    port: 3333
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/src/",
    filename: "bundle.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};

The application's entry point is set at the entry. The file specified at the entry is the first component that the Web page loads. Webpack will bundle all the JS and JSX files into the file that's specified in the output object. Webpack dev server is set to inline which allows a kind of reload on the fly and the application will be served at port 3333. In the module object, we specify the babel loader to use react and es2015 presets for converting ES6 and React code into code that the browser understands. The webpack plugins add the ability to use class properties and decorators.

Note: Babel presets are basically plugins that have been configured to do a particular task.

Hot reloading

The idea behind hot reloading is to keep the app running and to inject new versions of the files that you edited at runtime. This way, you don't lose any of your state which is especially useful if you are tweaking the UI.

Hot Reloading

(Source: Medium)

You can install hot module replacement like so:

npm install --save-dev babel-preset-react-hmre

Now, you can add it to the list of presets in the webpack.config.js file like so:

....
query: {
  presets: ['react', 'es2015', 'react-hmre'],
  plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}

Another option is to install react-hot-loader and add react-hot to the loader in the webpack.config.js file like so:

...
loader: ['babel-loader', 'react-hot']
...

To make things really easy, add a start option to the scripts object in package.json file like so:

{
  "scripts": {
    "start": "node_modules/.bin/webpack-dev-server --progress --inline --hot",
  }
}

The code above shows we have added the --hot option. This enables the hot reloading once you start your app by running npm run start.

Routing

Routing is an essential part of any application. The most popular choice for doing this in a ReactJS application is React Router. In fact, a lot of developers consider it the official routing system for ReactJS. When you want to deal with routing, you have to install the React Router module in your project as shown below:

npm install --save react-router

A sample implementation will look like this:

import React from 'react';
import { render } from 'react-dom';
import { browserHistory, Router, Route, IndexRoute } from 'react-router'

import App from '../components/App'
import Home from '../components/Home'
import About from '../components/About'
import Features from '../components/Features'

render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route path='features' component={Features} />
    </Route>
  </Router>,
  document.getElementById('app')
)

Routing

You actually might not need React Router. More info here

Internationalization (I18N)

There are over 7 billion people in the world. These people speak different languages. One way of making your app available to billions of people around the world is providing support for native languages in your app. In a ReactJS project, you can easily achieve that with a very good and well tested library react-intl. By default, react-intl ships with the locale data for English built-in to the library's runtime. This library provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations. Oh, it supports over 150 languages!

Internationalization Translation

UI Styling

In ReactJS projects, you can create custom stylesheets and UI Components. A developer that's looking to rapidly build an application might not have time to create UI components from scratch. The community has blessed us with two popular libraries that possess ready-made UI components for use in your application. React-Bootstrap has all of the bootstrap features written purely as reusable React Components. Material-UI is a set of React Components that implement Google's Material Design.

Material UI Material UI

React Bootstrap React Bootstrap

Material UI Code Example

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const MyAwesomeReactComponent = () => (
  <RaisedButton label="Default" />
);

export default MyAwesomeReactComponent;
import React from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import MyAwesomeReactComponent from './MyAwesomeReactComponent';

const App = () => (
  <MuiThemeProvider>
    <MyAwesomeReactComponent />
  </MuiThemeProvider>
);

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

One effective way of bootstrapping your ReactJS project is to start by designing your UI components and then glue them together, that way you can split up the initial setup effort into several small parts along the project lifecycle. Pure UI explains this in detail. I also recommend these tools: Carte-blanche, React Storybook, uiharness.com. They will help a lot!

Network Requests

In a situation where you have to fetch data from an external API e.g calling the Github API in your ReactJS application, there are several tools you can use. I highly recommend axios and superagent.

HTTP Request Example With Axios

import axios from 'axios';

function getRepos(username){
  return axios.get('https://api.github.com/users/${username}/repos');
}

function getUserInfo(username){
  return axios.get('https://api.github.com/users/${username}');
}

const helpers = {
  getGithubInfo(username) {
    return axios.all([getRepos(username), getUserInfo(username)])
      .then(arr => ({
      repos: arr[0].data,
      bio: arr[1].data
    }))
  }
};

export default helpers;

This is a helper utility that you can now call and render out in different ReactJS components within your app.

Flux Pattern - State Management

Flux is an application architecture for React that utilizes a unidirectional flow for building client-side web applications. With Flux, when a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected. When choosing a dispatcher for your app, Facebook's dispatcher library should come in handy. It's easy to instantiate and use. Alongside this library, you will need any good Javascript event library. NodeJS EventEmmiter module is a good option. You can install flux from npm, the dispatcher will be immediately available via var Dispatcher = require('flux').Dispatcher;. More details about the Flux pattern can be found here.

Data Flow (Source: Facebook)

Redux

Redux evolves the idea of Flux. It's a state management library with a minimal API but completely predictable behavior, so it is possible to implement logging, hot reloading, time travel, universal apps, record and replay, without any buy-in from the developer. You can also install it via NPM like so: npm install redux redux-devtools --save. Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. Redux has three fundamental principles:

  • Single source of truth
  • State is read-only
  • Changes are made with pure functions

Read more about Redux here. Here is also an awesome list of Redux examples and middlewares. Another alternative for state management within your ReactJS application is Alt. More information about Alt here.

Authentication

Authentication is an important part of any application. The best way to do user authentication for single page apps is via JSON Web Tokens (JWT). A typical authentication flow is this:

  • A user signs up/logs in, generates JWT id_token and access_token and returns them to the client
  • Store the JWT tokens on the client and send the access_token to the backend via headers/query parameters for future requests.

Authentication flow

How JSON Web Tokens work?

A comprehensive example of adding authentication to a ReactJS app is here. Using Redux? Here is a good example of setting up authentication in your ReactJS application.

Data Persistence

Without a backend, you can persist data in your Single Page App by using Firebase. In a Reactjs app, all you simply need is ReactFire. It is a ReactJS mixin for easy Firebase integration. With ReactFire, it only takes a few lines of JavaScript to integrate Firebase data into React apps via the ReactFireMixin.

npm install reactfire react firebase --save

TodoList Example

import React from 'react';

class TodoList extends React.Component {
  render() {
    var _this = this;
    var createItem = (item, index) => {
      return (
        <li key={ index }>
          { item.text }
          <span onClick={ _this.props.removeItem.bind(null, item['.key']) }
                style=>
            X
          </span>
        </li>
      );
    };

    return <ul>{ this.props.items.map(createItem) }</ul>;
  }
}

class TodoApp extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      items: [],
      text: ''
    };
  }

  componentWillMount() {
    this.firebaseRef = firebase.database().ref('todoApp/items');
    this.firebaseRef.limitToLast(25).on('value', function(dataSnapshot) {
      var items = [];
      dataSnapshot.forEach(childSnapshot => {
        const item = childSnapshot.val();
        item['.key'] = childSnapshot.key;
        items.push(item);
      });

      this.setState({
        items: items
      });
    }.bind(this));
  }

  componentWillUnmount() {
    this.firebaseRef.off();
  }

  onChange(e) {
    this.setState({text: e.target.value});
  }

  removeItem(key) {
    var firebaseRef = firebase.database().ref('todoApp/items');;
    firebaseRef.child(key).remove();
  }

  handleSubmit(e) {
    e.preventDefault();
    if (this.state.text && this.state.text.trim().length !== 0) {
      this.firebaseRef.push({
        text: this.state.text
      });
      this.setState({
        text: ''
      });
    }
  }

  render() {
    return (
      <div>
        <TodoList items={ this.state.items } removeItem={ this.removeItem } />
        <form onSubmit={ this.handleSubmit }>
          <input onChange={ this.onChange } value={ this.state.text } />
          <button>{ 'Add #' + (this.state.items.length + 1) }</button>
        </form>
      </div>
    );
  }
}

ReactDOM.render(<TodoApp />, document.getElementById('todoApp'));

More information about persisting your data using ReactFire here.

Testing

Most projects become a mountain of spaghetti code at some point during development due to lack of solid tests or no tests at all. ReactJS apps are no different, but this can be avoided if you know some core principles. When writing tests for ReactJS code, it is helpful to pull out any functionality that doesn't have to do with any UI components into separate modules, so that they can be tested separately. Tools for unit testing those functionalities are mocha, expect, chai, jasmine.

Testing becomes tricky in a ReactJS application when you have to deal with components. How do you test stateless components? How do you test components with state? Now, ReactJS provides a nice set of test utilities that allow us to inspect and examine the components we build. A particular concept worthy of mention is Shallow Rendering. Instead of rendering into a DOM the idea of shallow rendering is to instantiate a component and get the result of its render method. You can also check its props and children and verify they work as expected. More information here.

Facebook uses Jest to test React applications. AirBnB uses Enzyme. When bootstrapping your ReactJS application, you can set up any of these awesome tools to implement testing.

Generators and Boilerplates

A lot of tools have been mentioned in this post in relation to setting up different parts of a ReactJS app. If you don't intend writing your app from scratch, there are lots of generators and boilerplates that tie all these tools together to give you a great starting point for your app. One fantastic example is React Starter Kit. It has a Yeoman generator. It's an isomorphic web app boilerplate that contains almost everything you need to build a ReactJS app. Another boilerplate is React Static boilerplate, it helps you build a web app that can be hosted directly from CDNs like Firebase and Github Pages. Other alternatives are React redux starter kit and React webpack generator. Recently, a nice and effective tool called create-react-app was released by the guys at Facebook. It's a CLI tool that helps create React apps with no build configuration!

Aside: Authenticate a React App with Auth0

We can protect our applications and APIs so that only authenticated users can access them. Let's explore how to do this with a React application using Auth0.

Auth0 centralized login screen

We'll need an Auth0 account to manage authentication. To sign up for a free account, we can follow this link. Next, let's set up an Auth0 client app and API so Auth0 can interface with a React App.

Setting Up a Client App

  1. Let's go to our Auth0 Dashboard and click the "create a new client" button.
  2. Let's call our app as "React Demo" and select "Single Page Web Applications".
  3. In the Settings for our new Auth0 client app, let's add http://localhost:3000/callback to the Allowed Callback URLs.
  4. If desired, we can set up some social connections. We can then enable them for our app in the Client options under the Connections tab. The example shown in the screenshot above utilizes username/password database, Facebook, Google, and Twitter. For production, make sure to set up the correct social keys and do not leave social connections set to use Auth0 dev keys.

Dependencies and Setup

There are only two dependencies that we really need to install: auth0.js and history. To do that, let's issue npm install --save auth0-js history in the project root.

Note that, as we want to get the best security available, we are going to rely on the Centralized Login feature of Auth0. This method consists of redirecting users to a login page hosted by Auth0 that is easily customizable right from the Dashboard.

After installing it, we can create an authentication service to interface with the auth0.js script. Let's call this service Auth and create it in the src/Auth/ directory with the following code:

import history from '../history';
import auth0 from 'auth0-js';

export default class Auth {
  auth0 = new auth0.WebAuth({
    // the following three lines MUST be updated
    domain: 'bkrebs.auth0.com',
    audience: 'https://bkrebs.auth0.com/userinfo',
    clientID: '3co4Cdt3h3x8En7Cj0s7Zg5FxhKOjeeK',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid'
  });

  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        history.replace('/home');
      } else if (err) {
        history.replace('/home');
        console.log(err);
      }
    });
  }

  setSession(authResult) {
    // Set the time that the access token will expire at
    let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    // navigate to the home route
    history.replace('/home');
  }

  login() {
    this.auth0.authorize();
  }

  logout() {
    // Clear access token and ID token from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    // navigate to the home route
    history.replace('/home');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }
}

The Auth service just created contains functions to deal with various steps of the sign in/sign up process. The following list briefly summarizes these functions and their descriptions:

  • handleAuthentication: looks for the result of the authentication in the URL hash. Then, process the result with the parseHash method from auth0-js;
  • setSession: sets the user's access token, ID token, and the access token's expiry time;
  • login: initiates the login process, redirecting users to the Centralized Login page;
  • logout: removes the user's tokens and expiry time from browser storage;
  • isAuthenticated: checks whether the expiry time for the user's access token has passed;

Besides these functions, the class contains a field called auth0 that is initialized with values extracted from the Auth0 client. Let's keep in mind that we need to update them accordingly before proceeding.

Attentive readers probably noticed that the Auth service also imports a module called history that we haven't talked about. We can define this module in only two lines, but let's define it in a file to provide reusability. Let's call this file ./src/history/history.js and add the following code:

import createHistory from 'history/createBrowserHistory'

export default createHistory()

After creating both elements, we can refactor our App component to make use of the Auth service.

import React, { Component } from 'react';
import { Navbar, Button } from 'react-bootstrap';
import './App.css';

class App extends Component {
  goTo(route) {
    this.props.history.replace(`/${route}`)
  }

  login() {
    this.props.auth.login();
  }

  logout() {
    this.props.auth.logout();
  }

  render() {
    const { isAuthenticated } = this.props.auth;

    // ... render the view
  }
}

export default App;

Note that we are passing this service through props. Therefore, when including the App component, we need to inject Auth into it: <App auth={auth} />.

Considering that we are using the Auth0 Centralized Login page, our users are taken away from the application. However, after they authenticate, users automatically return to the callback URL that we set up previously (http://localhost:3000/callback). This means that we need to create a component responsible for this URL:

import React, { Component } from 'react';
import loading from './loading.svg';

class Callback extends Component {
  render() {
    const style = //...

    return (
      <div style={style}>
        <img src={loading} alt="loading"/>
      </div>
    );
  }
}

export default Callback;

This component can be just a loading indicator that keeps spinning while the application sets up a client-side session for the users. After the session is set up, we can redirect users to another route.

Please, refer to the official Quick Start Guide to see, step by step, how to properly secure a React application. Besides the steps shown in this section, the guide also shows:

Conclusion

There are several tools that will help bootstrap your React app, we looked at a couple that we consider quite good and will have your application up and running in no time. But feel free to search for your own tools, and if you think that we are missing something, let us know in the comments. Setting up a React project should be painless!

"Setting up a React project should be painless!"