Chapter 1. Hello World

Let’s get started on the journey to mastering application development using React. In this chapter, you will learn how to set up React and write your first “Hello World” web app.

Setup

First things first: you need to get a copy of the React library. There are various ways to go about it. Let’s go with the simplest one that doesn’t require any special tools and can get you learning and hacking away in no time.

Create a folder for all the code in the book in a location where you’ll be able to find it.

For example:

$ mkdir ~/reactbook

Create a /react folder to keep the React library code separate.

$ mkdir ~/reactbook/react

Next, you need to add two files: one is React itself, the other is the ReactDOM add-on. You can grab the latest 17.* versions of the two from the unpkg.com host, like so:

$ curl -L https://unpkg.com/react@17/umd/react.development.js > ~/reactbook/react/react.js
$ curl -L https://unpkg.com/react-dom@17/umd/react-dom.development.js > ~/reactbook/react/react-dom.js

Note that React doesn’t impose any directory structure; you’re free to move to a different directory or rename react.js however you see fit.

You don’t have to download the libraries; you can use them directly from unpkg.com. However, having them locally makes it possible to learn anywhere and without an internet connection.

Note

The @17 in the URLs shown in the preceding example gets you a copy of the latest React 17, which is current at the time of writing this book. Omit @17 to get the latest available React version. Alternatively, you can explicitly specify the version you require, for example @17.0.2.

Hello React World

Let’s start with a simple page in your working directory (~/reactbook/01.01.hello.html):

<!DOCTYPE html>
<html>
  <head>
    <title>Hello React</title>
    <meta charset="utf-8">
  </head>
  <body>
    <div id="app">
      <!-- my app renders here -->
    </div>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>
    <script>
      // my app's code
    </script>
  </body>
</html>
Note

You can find all the code from this book in the accompanying repository.

Only two notable things are happening in this file:

  • You include the React library and its Document Object Model (DOM) add-on (via <script src> tags)

  • You define where your application should be placed on the page (<div id="app">)

Note

You can always mix regular HTML content as well as other JavaScript libraries with a React app. You can also have several React apps on the same page. All you need is a place in the DOM where you can point React to and say “do your magic right here.”

Now let’s add the code that says “hello”—update 01.01.hello.html and replace // my app's code with:

ReactDOM.render(
  React.createElement('h1', null, 'Hello world!'),
  document.getElementById('app')
);

Load 01.01.hello.html in your browser and you’ll see your new app in action (as depicted in Figure 1-1).

rur2 0101
Figure 1-1. “Hello world!” in action

Congratulations, you’ve just built your first React application!

Figure 1-1 also shows the generated code in Chrome DevTools where you can see that the contents of the <div id="app"> placeholder was replaced with the contents generated by your React app.

What Just Happened?

There are a few points of interest in the code that made your first app work.

First, you see the use of the React object. All of the APIs available to you are accessible via this object. The API is intentionally minimal, so there are not a lot of method names to remember.

You can also see the ReactDOM object. It has only a handful of methods, render() being the most useful. ReactDOM is responsible for rendering the app in the browser. You can, in fact, create React apps and render them in different environments outside the browser—for example in canvas, or natively in Android or iOS.

Next, there is the concept of components. You build your UI using components and you combine these components in any way you see fit. In your applications, you’ll end up creating your custom components, but to get you off the ground, React provides wrappers around HTML DOM elements. You use the wrappers via the React.createElement function. In this first example, you can see the use of the h1 element. It corresponds to the <h1> in HTML and is available to you using a call to React.createElement('h1').

Finally, you see the good old document.getElementById('app') DOM access. You use this to tell React where the application should be located on the page. This is the bridge crossing over from the DOM manipulation as you know it to React-land.

Once you cross the bridge from DOM to React, you don’t have to worry about DOM manipulation anymore, because React does the translation from components to the underlying platform (browser DOM, canvas, native app). In fact, not worrying about the DOM is one of the great things about React. You worry about composing the components and their data—the meat of the application—and let React take care of updating the DOM most efficiently. No more hunting for DOM nodes, firstChild, appendChild() and so on.

Note

You don’t have to worry about DOM, but that doesn’t mean you cannot. React gives you “escape hatches” if you want to go back to DOM-land for any reason you may need.

Now that you know what each line does, let’s take a look at the big picture. What happened is this: you rendered one React component in a DOM location of your choice. You always render one top-level component, and it can have as many child (and grandchild, etc.) components as needed. Even in this simple example, the h1 component has a child—the “Hello world!” text.

React.createElement()

As you now know, you can use a number of HTML elements as React components via the React.createElement() method. Let’s take a close look at this API.

Remember, the “Hello world!” app looks like this:

ReactDOM.render(
  React.createElement('h1', null, 'Hello world!'),
  document.getElementById('app')
);

The first parameter to createElement is the type of element to be created. The second (which is null in this case) is an object that specifies any properties (think DOM attributes) that you want to pass to your element. For example, you can do:

React.createElement(
  'h1',
  {
    id: 'my-heading',
  },
  'Hello world!'
),

The HTML generated by this example is shown in Figure 1-2.

rur2 0102
Figure 1-2. HTML generated by a React.createElement() call

The third parameter ("Hello world!" in this example) defines a child of the component. The simplest case is just a text child (a Text node in DOM-speak) as you see in the preceding code. But you can have as many nested children as you like and you pass them as additional parameters. For example:

React.createElement(
  'h1',
  {id: 'my-heading'},
  React.createElement('span', null, 'Hello'),
  ' world!'
),

Another example, this time with nested components (result shown in Figure 1-3) is as follows:

React.createElement(
  'h1',
  {id: 'my-heading'},
  React.createElement(
    'span',
    null,
    'Hello ',
    React.createElement('em', null, 'Wonderful'),
  ),
  ' world!'
),
rur2 0103
Figure 1-3. HTML generated by nesting React.createElement() calls

You can see in Figure 1-3 that the DOM generated by React has the <em> element as a child of the <span> which is in turn a child of the <h1> element (and a sibling of the “world” text node).

JSX

When you start nesting components, you quickly end up with a lot of function calls and parentheses to keep track of. To make things easier, you can use the JSX syntax. JSX is a little controversial: people often find it repulsive at first sight (ugh, XML in my JavaScript!), but indispensable after.

Note

It’s not quite clear what the acronym JSX stands for, but it’s most likely JavaScriptXML or JavaScript Syntax eXtension. The official home of the open-source project is https://facebook.github.io/jsx.

Here’s the previous snippet but this time using JSX syntax:

ReactDOM.render(
  <h1 id="my-heading">
    <span>Hello <em>Wonderful</em></span> world!
  </h1>,
  document.getElementById('app')
);

This is much more readable. This syntax looks very much like HTML and you already know HTML. However it’s not valid JavaScript that browsers can understand. You need to transpile this code to make it work in the browser. Again, for learning purposes, you can do this without special tools. You need the Babel library which translates cutting-edge JavaScript (and JSX) to old school JavaScript that works in ancient browsers.

Setup Babel

Just like with React, get a local copy of Babel:

$ curl -L https://unpkg.com/babel-standalone/babel.min.js > ~/reactbook/react/babel.js

Then you need to update your learning template to include Babel. Create a file 01.04.hellojsx.html like so:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello React+JSX</title>
    <meta charset="utf-8">
  </head>
  <body>
    <div id="app">
      <!-- my app renders here -->
    </div>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>
    <script src="react/babel.js"></script>
    <script type="text/babel">
      // my app's code
    </script>
  </body>
</html>
Note

Note how <script> becomes <script type="text/babel">. This is a trick where, by specifying an invalid type, the browser ignores the code. This gives Babel a chance to parse and transform the JSX syntax into something the browser can run.

Hello JSX World

With this bit of setup out of the way, let’s try JSX. Replace the // my app's code part in the preceding HTML with:

ReactDOM.render(
  <h1 id="my-heading">
    <span>Hello <em>JSX</em></span> world!
  </h1>,
  document.getElementById('app')
);

The result of running this in the browser is shown in Figure 1-4.

rur2 0104
Figure 1-4. Hello JSX world

On Transpilation

It’s great that you got the JSX and Babel to work, but maybe a few more words won’t hurt, especially if you’re new to Babel and the process of transpilation. If you’re already familiar, feel free to skip this part where we familiarize a bit with the terms JSX, Babel, and transpilation.

JSX is a separate technology from React and is completely optional. As you see, the first examples in this chapter didn’t even use JSX. You can opt into never coming anywhere near JSX at all. But it’s very likely that once you try it, you won’t go back to function calls.

The process of transpilation is a process of taking source code and rewriting it to accomplish the same results but using syntax that’s understood by older browsers. It’s different than using polyfills. An example of a polyfill is adding a method to Array.prototype such as map(), which was introduced in ECMAScript5, and making it work in browsers that support only ECMAScript3. A polyfill is a solution in pure JavaScript-land. It’s a good solution when adding new methods to existing objects or implementing new objects (such as JSON). But it’s not sufficient when new syntax is introduced into the language. Any new syntax in the eyes of a browser that does not support it is just invalid and throws a parse error. There’s no way to polyfill it. New syntax, therefore, requires a compilation (transpilation) step so it’s transformed before it’s served to the browser.

Transpiling JavaScript is getting more and more common as programmers want to use the latest JavaScript (ECMAScript) features without waiting for browsers to implement them. If you already have a build process set up (that does, for example, minification or any other code transformation), you can simply add the JSX step to it. Assuming you don’t have a build process, you’ll see later in the book the necessary steps of setting one up.

For now, let’s leave the JSX transpilation on the client side (in the browser) and move on with learning React. Just be aware that this is only for education and experimentation purposes. Client-side transforms are not meant for live production sites as they are slower and more resource intensive than serving already transpiled code.

Next: Custom Components

At this point, you’re done with the bare-bones “Hello world” app. Now you know how to:

  • Set up the React library for experimentation and learning (it’s really just a question of a few <script> tags)

  • Render a React component in a DOM location of your choice (e.g., ReactDOM.render(reactWhat, domWhere))

  • Use built-in components, which are wrappers around regular DOM elements (e.g., React.createElement(element, attributes, content, children))

The real power of React, though, comes when you start using custom components to build (and update!) the user interface (UI) of your app. Let’s learn how to do just that in the next chapter.

Get React: Up & Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.