2

Building Your First React App

Thanks to the previous chapter, you probably now know all about the backstory of React and how it helps even your most complex user interfaces sing. For all the awesomeness that React brings to the table, getting started with it (kind of like this sentence) is not the most straightforward. It has a steep learning curve filled with many small and big hurdles, as in Figure 2.1.

A figure shows a tiny square and a large circle placed side by side. The square represents a small hurdle and the circle represents a big hurdle.

Figure 2.1 Hurdles come in a variety of sizes. Some are big. Some are small.

In this chapter, we start at the very beginning and get our 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 chapter, 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 in future chapters.

Dealing with JSX

Before we start building our 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 2.2).

An illustration shows a web app that's titled "LOREMIPSUM." The app typically contains a search bar, and several contents that displayed are thumbnails. This app, indicated as a totally sweet web app, is identified to be made of HTML, CSS, and JavaScript.

Figure 2.2 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, “Introducing React,” 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, we need a way to convert our JSX into plain old JavaScript that your browser can understand (see Figure 2.3).

The illustration shows the "React (JSX)" editor window on the left and the finished web app on the right. An arrow indicates that JSX needs to turn into something that the browser can understand before resulting in the finished app.

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

If we don’t do this, our React app simply won’t work. That’s not cool. Fortunately, we have 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 of your JSX is automatically converted into JS 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 in our world, but let’s talk about 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 JS, this approach enables you to take advantage of modules, better build tools, and 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 JS on page load, and your React app comes to life without you having to do anything special to your development environment.

For our introductory look at React, we are going to use the second solution. You might be wondering why we don’t always use the second solution. The reason is that your browser takes a performance hit each time it translates JSX into JS. That is totally acceptable when learning how to use React, but it is totally not acceptable when deploying your app for real-life use. Because of that lack of acceptability, we will revisit all of this later, to look at the first solution and how to set up your development environment after you’ve gotten your feet comfortably wet in React.

Getting Your React On

In the previous section, we looked at the two ways you have for ensuring that your React app ends up as something your browser understands. In this section, we put all those words into practice. First, you need a blank HTML page as your starting point.

Create a new HTML document with the following contents:

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:

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:

Here you’re adding a reference to the Babel JavaScript compiler (http://babeljs.io/). 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:

If you preview your page right now, you’ll notice that this page is still blank, with nothing visible going on. That’s okay. We’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:

Don’t worry if none of this makes sense at this point. Our goal is to get something to display onscreen first, and we’ll make sense of what we 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:

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 in Figure 2.4.

A screenshot shows the "start.htm" page. The text "Sherlock Holmes" appears on the screen in bold.

Figure 2.4 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.

The render method takes two arguments:

1. The HTML-like elements (a.k.a. JSX) you want to output

2. The location in the DOM where React will render the JSX into

Here’s what our render method looks like:

Our 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. 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 super-awesome 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 our DOM. In our 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:

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

The JavaScript looks new and shiny thanks to JSX, but the end 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 our app behaves and looks.

Changing the Destination

First we’ll 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 going to be mixing React with other JS libraries and frameworks. The recommended path is to create a separate element that you will treat as a new root element. This element will serve 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:

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

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

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, our names show up in whatever default h1 styling the browser provides. That’s just terrible, so let’s fix that by adding some CSS. Inside your head tag, let’s add a style block with the following CSS:

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 2.5).

The screenshot of the "react_tutorial.htm Preview" window shows the text “Batman” displayed in color. The background of the text appears better too.

Figure 2.5 The result of adding the CSS.

This works because, after running all the React code, the DOM’s body contains our 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 end result of your React app is still going to be made up of some 100% organic (and cage-free!) HTML, CSS, and JavaScript. If we had to see what this transpiled JavaScript looks like, it would look a bit like the following:

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

Conclusion

If this is your first time building a React app, we 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 we 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 we 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.

In future chapters, we spend some time diving deeper into JSX and going beyond the render method as we look at all the important things that make React tick.

Note: If you run into any issues, ask!

If you have any questions or your code isn’t running like you expect, don’t hesitate to ask! Post on the forums at https://forum.kirupa.com and get help from some of the friendliest and most knowledgeable people the Internet has ever brought together!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
54.205.238.173