React tutorial: Get started with the React.js JavaScript library

Learn the key concepts behind React and how to use JSX elements and components to build lean and fast web front ends

Get started with React: The InfoWorld tutorial
Thinkstock

React, also known as ReactJS, is an open source JavaScript library for building user interfaces, often for single-page applications or to add interactive views to existing web applications built in a variety of architectures. The React project originated at Facebook; the open source project has a BSD license and a patent rights grant from Facebook.

React is not an end-to-end JavaScript application framework. It has no support for models or controllers, although there are projects related to React that cover these functions, along with routing. You can easily combine React with other architectures.

Why React?

One of the top reasons people cite as a reason to use React is actually controversial: JSX allows you to mix JavaScript and HTML in a single component, which is transformed into pure JavaScript as part of the build step. At first hearing, that sounds like a terrible idea because it violates the principle of separation of concerns.

React fans respond by pointing out, reasonably, that UI presentation and UI interaction are closely linked concerns that don’t really need to be separated, and that in practice JSX makes writing user interfaces simpler. They go on to add that purists can write React completely in JavaScript if they want; it just takes more code and isn’t as easy to write or read.

The second big reason people like React is that it’s fast and efficient, especially for the case where data changes over time. React maintains its own virtual DOM in memory, and updates the browser DOM as needed. The React team talks about re-render times on the order of 1 millisecond, which is so fast that React doesn’t need to worry about explicit data bindings.

react debug tab IDG

A third reason to like React is that you can run it on the server if you wish, instead of the client. Doing that is usually even faster than running it on the client, and has the additional benefit of generating normal HTML that can be seen by search engines and used for SEO.

Fourth, React has a nice set of tools in its ecosystem. For example, the official React Developer Tools extension for Google Chrome (shown in the screenshot above) lets you see the React in-memory component hierarchies and inspect and edit React component properties and state.

Finally, if you learn to use React for websites, you can transfer those skills to React Native and use them for mobile apps on Android and iOS.

Some major sites built using React include parts of Facebook, all of Instagram, and at least some of Khan Academy and the New York Times. Major mobile apps built using React Native include Facebook Ads Manager and Discovery VR.

React vs. Angular

People often try to compare React with Angular and choose just one. The simplest way to look at that comparison is that React has one job, UI, the “V” (for view) in MVC, while Angular implements the whole kit and caboodle. Another way to look at it is that React is simpler to learn than Angular, because there are fewer concepts in React to grok. A third way to look at it is that React adds HTML to JavaScript through JSX, while Angular adds JavaScript to HTML through templates and components. (For a closer look at Angular, see “Get started with Angular: The InfoWorld tutorial.”)

Ultimately, which framework you use may depend on your company’s standards, or the prejudices of your pointy-haired boss. If it comes down to your individual druthers, React may suit you better if you think in terms of code, whereas Angular may suit you better if you think in terms of markup.

Install React, maybe

You don’t actually have to install React to get a feel for it: You can play with it in CodePen, as shown in the screenshot below. The two key things to notice in the screenshot are the ReactDOM.render() call in the JavaScript at the right, which puts its output into the 'root' element, and the "root" div in the HTML at left. The output at the bottom is just what you would expect. Note that there is no visible link from the HTML to the JavaScript—that link is created by the tooling in the environment.

react hello codepen IDG

If you want to develop anything seriously with React, you should install it on your machine, using either NPM or Yarn. There are several additional choices to make: how to configure and invoke the Babel compiler that turns JSX into plain JavaScript; whether and how to bundle your JavaScript with a tool such as Browserify or Webpack; whether to include a local server and automatic refresh tools in your development build chain; whether or not to start with the Create React App front-end starter application; and how to clean up and package your app for production use. There are so many helpful, powerful tools for React that learning to use and configure them properly can be challenging.

Rather than overwhelm you with those choices prematurely, let’s just take a baby step up from CodePen and look at a single-file React app. You can download this HTML file and open it in your browser from the local file system or a local web server. Note that it is not suitable for use in production, for reasons I will explain.

react hello code IDG

The code in the text/babel script, lines 14 to 17, should look familiar. It is identical to what we saw in the CodePen example. Line 11 should also look familiar. It is simply a div element named root.

What about all the script imports in lines 6 through 8? The first two are development (easy to read but un-minimized) distributions of React and React-DOM, which are the core packages we need. The third is a minimized version of the standalone Babel compiler, the use of which is triggered by the text/babel type of the script starting at line 12.

The output of all of this is of course just “Hello, world!” in an H1 style:

react hello output IDG

While running this from a file URL as shown directly above works OK, for the best development experience you should run it in an HTTP server, as shown in the first screenshot in this article, where I was able to debug React’s DOM. If you use the simple HTTP server included with Python 3, as I did, the command line used to start the server is

$ python -m http.server 8000

I opened the file at http://localhost:8000/hello.html.

The unified HTML and JSX file seems to work fine, so why not use it in production? Basically, because it’s slow. You don’t want to incur the overhead of downloading all of React, even though it’s coming from a CDN, and you especially don’t want to incur the overhead of using uncompressed versions in production, despite their convenience for debugging.

Further, although compiling three lines of JSX code to JavaScript isn’t a big deal, real production applications use way more than three lines of JSX, so the Babel compilation overhead should properly be incurred at build time, not run time. And finally, you are going to want your JSX components to live in their own files, for reusability.

JSX elements and components

So what are JSX components, beyond being a way to add HTML to JavaScript?

As Eric Elliott wrote in JavaScript Scene in 2015, “JSX looks like an abomination—but it’s good for you.” Eric goes on to say of a React component example with inline JSX: “At first glance, this looks like the unholy love child of 1990’s DHTML and 2015 ES6. We’re talking some Frankenstein madness… right?”

It actually bothers me that Elliott went on to refute his point, because that was such a good description of my own first impression of inline JSX. But now let’s get serious: What is JSX really? Aside from appearing to be neither fish nor fowl, JSX is an extension to JavaScript syntax. It looks a little like a template language, especially since it incorporates handlebars notation, but it compiles to JavaScript (with Babel, as I’ve already mentioned.)

Here’s a basic one-line example of a JSX element:

const element =<h1>Hello, world!</h1>;

It looks a little like JavaScript, but then it gets really weird. Why isn’t that HTML a string enclosed in quotes? Perhaps the Babel compiler output will help:

"use strict"; 

var element = React.createElement(
  "h1",
  null,
  "Hello, world!"
);

The JSX expression on the right-hand side of the example compiles to a React.createElement() call. We can infer a rule about JSX components from that: The React library always needs to be in scope. Also, the fact that the element created resides in the React virtual DOM bears emphasizing.

There are explicit rules about JSX. One is that you can embed any JavaScript expression in JSX by wrapping it in curly braces. Another is that after compilation, JSX expressions become regular JavaScript objects. A third rule is that you may use quotes to specify string literals as attributes, or curly braces to embed a JavaScript expression in an attribute, but not both in the same attribute.

After compilation, JSX expressions become regular JavaScript objects. That means you can use JSX inside of if statements and for loops, or anywhere else you could put a JavaScript expression.

Returning to the "Hello, world!" element above, after React.createElement() runs, it creates a data structure that contains a type (in this case "h1") and properties (props) such as a className (in this case null) and children (in this case "Hello, world!"). Elements represent what you want to see on the screen. You can explicitly ask React to render an element into the browser DOM at the root element by calling:

ReactDOM.render(
  element,
  document.getElementById('root')
);

While you can call ReactDOM.render() whenever you like, most React apps only call it once.

Now that you have some grasp of React elements, we can explain React components, which are JavaScript functions or ES6 classes that accept arbitrary inputs (props) and return the React elements that describe what should appear on the screen. The following two Welcome components are the same at the end of the day, except that one is written in functional style and one is expressed as a class:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

——

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Once you have defined a component, you can use it as an element (since it returns an element). For example,

const element = <Welcome name="Sara" />;

As a matter of style, React component names are always Capitalized, and React property names (props) are always in camelCase style.

Components can be composed of other components, just as functions in a functional language can be composed of other functions. Components must also be pure functions (another attribute of a functional language), which means that components may not modify their input props. If you’re getting the idea that functional languages influenced the design of React, you’re not mistaken.

Because components can return only a single root element, you may have to group internal component elements under a single div element:

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

Two important features of React components, local state and lifecycle hooks, can be used only if the components are classes. Here is an example of a Clock component class with both local state and lifecycle hooks:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

In the code above, the Clock class constructor sets the initial state (this.state) to the current date and time. The lifecycle hooks are the componentDidMount() and componentWillUnmount() methods. The first sets up a timer whenever the clock is rendered to the DOM, while the second clears the timer when the clock (i.e. the DOM created by the Clock class) is removed.  

It’s worth going through the entire React Quick Start tutorial to understand how this component works; in the above discussion I have only hit the high points. Pay special attention when you get to the discussion of composition versus inheritance, as using inheritance is frowned upon in the React style. Also take some time with the Thinking in React discussion, which gives you a step-by-step method for building a React application starting with a mock and a JSON API.

I consider the React Quick Start pretty good, but I have to say that by relying on CodePen it goes too far in the direction of shielding you from the nuts and bolts of a real development environment.

Next steps

As a prerequisite before going on, install NPM and Node.js if they are not already on your machine. I recommend using the LTS (long-term support) versions.

As the actual next step, you should install the Create React App starter application on your machine and create a project with it:

npm install -g create-react-app
cd ~/work
create-react-app my-app
cd my-app/
npm start

Then open http://localhost:3000/ to see your app, and start modifying the code to get what you want. When you’re ready to deploy your app, you can create a minified bundle with npm run build.

Note that the starter app uses Babel to compile your JSX and ES6 into JavaScript and Webpack to bundle your JavaScript, but hides them from you to reduce the frustration of setting them up. It’s worth digging into how those tools are configured at some point, rather than treating the advanced development environment as though it were magic. After all, you will probably want to use the full React environment later on, instead of the starter app, and the starter app’s setup might be a good model on which to build.

When you want to combine React with other environments that handle the back end of the application, remember that Google search is your friend. There are many good tutorials about using React with other architectures, including Flux, Redux, Ruby on Rails, ASP.NET, and Angular.

Copyright © 2017 IDG Communications, Inc.