Tutorial: Programming in React for beginners

Here, I start at the very beginning so you can get your hands dirty by building a simple React app

Tutorial: Programming in React for beginners
Petra (CC0)

For all the awesomeness that React brings to the table, getting started with it is not the most straightforward process. It has a steep learning curve filled with many small and big hurdles.

Here, I start at the very beginning so you can get your hands dirty by building a simple React app. You’ll encounter some of these hurdles head-on, and some of these hurdles you’ll skip over—for now. By the end of this article, not only will you have built something you can proudly show off to your friends and family, but you’ll have set yourself up nicely for diving deeper into all that React offers.

Dealing with JSX

Before you start building your app, there’s an important point to cover first: React isn’t like many JavaScript libraries you might have used. It doesn’t get too happy when you simply refer to code you’ve written for it using a script tag. React is annoyingly special that way, and it has to do with how React apps are built.

As you know, your web apps (and everything else your browser displays) are made up of HTML, CSS, and JavaScript (see Figure 1).

react fig1 Pearson Addison-Wesley

Figure 1. Web apps are built in HTML, CSS, and JavaScript.

It doesn’t matter whether your web app was written using React or some other library, such as Angular, Knockout, or jQuery. The end result has to be some combination of HTML, CSS, and JavaScript; otherwise, your browser really won’t know what to do.

Now, here’s where the special nature of React comes in. Besides normal HTML, CSS, and JavaScript, the bulk of your React code will be written in JSX. As I mentioned in Chapter 1, JSX is a language that allows you to easily mix JavaScript and HTML-like tags to define user interface (UI) elements and their functionality. That sounds cool and all (and you’ll see JSX in action in just a few moments), but there’s a slight problem: Your browser has no idea what to do with JSX.

To build a web app using React, you need a way to convert your JSX into plain old JavaScript that your browser can understand (see Figure 2).

react fig2 Pearson Addison-Wesley

Figure 2. JSX needs to turn into something our browser understands.

If you don’t do this, your React app simply won’t work. That’s not cool. Fortunately, there are two solutions to this:

  1. Set up a development environment around Node and a handful of build-tools. In this environment, every time you perform a build, all your JSX is automatically converted into JavaScript and placed on disk for you to reference like any plain JavaScript file.
  2. Let your browser automatically convert JSX to JavaScript at runtime. You specify your JSX directly, just as you would any old piece of JavaScript, and your browser takes care of the rest.

Both of these solutions have a place, but let’s explore the impact of each.

The first solution, while a bit complicated and time-consuming at first, is the way modern web development is done these days. Besides compiling (transpiling, to be more accurate) your JSX to JavaScript, this approach enables you to take advantage of modules, better build tools, and do a bunch of other features that make building complex web apps somewhat manageable.

The second solution provides a quick and direct path in which you initially spend more time writing code and less time fiddling with your development environment. To use this solution, all you do is reference a script file. This script file takes care of turning the JSX into JavaScript on page load, and your React app comes to life without you having to do anything special to your development environment.

In this introductory look at React, I am using the second solution.You might be wondering why you don’t always use the second solution. The reason is that your browser takes a performance hit each time it translates JSX into JavaScript. That is totally acceptable when learning how to use React, but it is totally not acceptable when deploying your app for real-life use.

Getting your React on

First, you need a blank HTML page as your starting point. So, create a new HTML document with the following contents:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>React! React! React!</title>
</head>

<body>
  <script>

  </script>
</body>

</html>

This page has nothing interesting or exciting going for it, but let’s fix that by adding a reference to the React library. Just below the title, add these two lines:

<script src="https://unpkg.com/react@16/umd/react.development.js">
</script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
</script>

These two lines bring in both the core React library and the various things React needs to work with the DOM. Without them, you aren’t building a React app at all.

Now, you aren’t done yet. You need to reference one more library. Just below these two script tags, add the following line:

<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js">
</script>

Here you’re adding a reference to the Babel JavaScript compiler. Babel does many cool things, but the one we care about is its capability to turn JSX into JavaScript.

At this point, your HTML page should look as follows:

<!DOCTYPE html> <html>
<head>
  <meta charset="utf-8">
  <title>React! React! React!</title>
  <script src="https://unpkg.com/react@16/umd/react.development.js">
</script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
</script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js">
</script>
</head>

<body>
  <script>

  </script>
</body>

</html>

If you preview your page right now, you’ll notice that this page is still blank, with nothing visible going on. That’s okay. You’re going to fix that next.

Displaying your name

Now you’re going to use React to display your name onscreen. You do that by using a method called render. Inside your empty script tag in the body, add the following:

ReactDOM.render(
  <h1>Sherlock Holmes</h1>,
   document.body
);

Don’t worry if none of this makes sense at this point. The goal is to get something to display onscreen first, and you’ll be able to make sense of what you did afterward. Now, before previewing this in the page to see what happens, you need to designate this script block as something that Babel can work its magic on. You do that is by setting the type attribute on the script tag to a value of text/babel:

<script type="text/babel">
  ReactDOM.render(
    <h1>Sherlock Holmes</h1>,
    document.body
  );
</script>

After you’ve made that change, preview what you have in your browser. You’ll see the words Sherlock Holmes printed in giant letters, as shown in Figure 3.

react fig3 Pearson Addison-Wesley

Figure 3. Your browser should display “Sherlock Holmes.”

Congratulations! You’ve just built an app using React.

As apps go, this isn’t all that exciting. Chances are, your name isn’t even Sherlock Holmes. This app doesn’t have much going for it, but it does introduce you to one of the most frequently used methods you’ll use in the React universe: the ReactDOM.render method.

Therender method takes two arguments:

  1. The HTML-like elements (aka. JSX) you want to output.
  2. The location in the DOM where React will render the JSX into.

Here’s what the render method looks like:

ReactDOM.render(
  <h1>Sherlock Holmes</h1>,
  document.body
);

The first argument is the text Sherlock Holmes wrapped inside some h1 tags. This HTML-like syntax inside your JavaScript is what JSX is all about. We’ll spend a lot more time drilling into JSX a bit later, but I should mention this up front: It is every bit as crazy as it looks. Whenever I see brackets and slashes in JavaScript, a part of me dies on the inside because of all the string escaping and quotation mark gibberish I will need to do. But with JSX, you do none of that. You just place your HTML-like content as is, just like you’ve done here. Magically (like the superawesome kind involving dragons and laser beams), it all works.

The second argument is document.body. There’s nothing crazy or bizarre about this argument. It simply specifies where the converted markup from the JSX will end up living in your DOM. In this example, when the render method runs, the h1 tag (and everything inside it) is placed in our document’s body element.

Now, the goal of this exercise wasn’t to display a name on the screen. It was to display your name. Go ahead and modify your code to do that. In my case, the render method will look as follows:

ReactDOM.render(
  <h1>Batman</h1>,
  document.body
);

Well, it would look like that if my name were Batman! Anyway, if you preview your page now, you’ll see your name displayed instead of Sherlock Holmes.

It’s all still familiar to the browser

The JavaScript looks new and shiny, thanks to JSX, but the result your browser sees is nice and clean HTML, CSS, and JavaScript. To see this for yourself, let’s make a few alterations to how the app behaves and looks.

Changing the destination

First, change where the JSX gets output. Using JavaScript to place things directly in your body element is never a good idea. A lot can go wrong, especially if you’re mixing React with other JavaScript libraries and frameworks. The recommended path is to create a separate element that you treat as a new root element. This element serves as the destination your render method will use. To make this happen, go back to the HTML and add a div element with an id value of container:

<body>
<div id="container"></div>
  <script type="text/babel">
    ReactDOM.render(
      <h1>Batman</h1>,
      document.body
   );
  </script>
</body>

With the container div element safely defined, modify the render method to use it instead of document.body. Here’s one way of doing this:

ReactDOM.render(
  <h1>Batman</h1>,
  document.querySelector("#container")
);

Another option is to do some things outside the render method itself:

vardestination = document.querySelector("#container");

ReactDOM.render(
  <h1>Batman</h1>,
  destination
);

Notice that the destination variable stores the reference to your container DOM element. Inside the render method, you simply reference the same destination variable instead of writing the full element-finding syntax as part of the argument itself. The reason for this is simple: I want to show you that you’re still writing JavaScript and that render is just another boring old method that happens to take two arguments.

Styling it up

Time for the last change before we call it a day. Right now, the names show up in whatever default h1 styling the browser provides. That’s just terrible, so fix that by adding some CSS. Inside your head tag, add a style block with the following CSS:

<style>
  #container {
    padding: 50px;
    background-color: #EEE;
  }
  #container h1 {
    font-size: 144px;
    font-family: sans-serif;
    color: #0080A8;
  }
</style>

After you’ve added everything, preview your page. Notice that the text appears to have a little more purpose than it did earlier, when it relied entirely on the browser’s default styling (see Figure 4).

react fig4 Pearson Addison-Wesley

Figure 4.The result of adding the CSS.

This works because, after running all the React code, the DOM’s body contains your container element with an h1 tag inside it. It doesn’t matter that the h1 tag was defined entirely inside JavaScript in this JSX syntax or that your CSS was defined well outside the render method. The result of your React app is still going to be made up of some 100-percent organic (and cage-free!) HTML, CSS, and JavaScript. If you could see what this transpiled JavaScript looks like, it would look a bit like the following:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>React! React! React!</title>
  <script src="https://unpkg.com/react@16/umd/react.development.js">
</script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
</script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js">
</script>

<style>
  #container {
    padding: 50px;
    background-color: #EEE;
  }
  #container h1 {
    font-size: 144px;
    font-family: sans-serif;
    color: #0080A8;
  }
  </style>
</head>

<body>
<div id="container"></div>
  <script type="text/babel">
    var destination = document.querySelector("#container");

    ReactDOM.render(React.createElement(
      "h1",
      null,
      "Batman"
    ), destination);
  </script>
</body>

</html>

Notice that there’s nary a trace of React-like code in sight. (Also, we all should use the word nary more often in everyday conversation!)

Conclusion

If this is your first time building a React app, you’ve covered a lot of ground here. One of the biggest takeaways is that React is different than other libraries because it uses a whole new language called JSX to define what the visuals will look like. You got a very small glimpse of that here when you defined the h1 tag inside the render method.

JSX’s impact goes beyond how you define your UI elements. It also alters how you build your app as a whole. Because your browser can’t understand JSX in its native representation, you need to use an intermediate step to convert that JSX into JavaScript. One approach is to build your app to generate the transpiled JavaScript output to correspond to the JSX source. Another approach (the one you used here) is to use the Babel library to translate the JSX into JavaScript on the browser itself. While the performance hit of doing this is not recommended for live/production apps, when you’re familiarizing yourself with React, you can’t beat the convenience.

Copyright © 2018 IDG Communications, Inc.