- Dealing with JSX
- Getting Your React On
- Displaying Your Name
- It’s All Still Familiar
- Conclusion
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. 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:
<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 in Figure 2.4.
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:
The HTML-like elements (a.k.a. JSX) you want to output
The location in the DOM where React will render the JSX into
Here’s what our render method looks like:
ReactDOM.render( <h1>Sherlock Holmes</h1>, document.body );
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:
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.