What is JSX?

In this section, we'll implement the obligatory hello world JSX application. At this point, we're just dipping our toes into the water; more in-depth examples will follow. We'll also discuss what makes this syntax work well for declarative UI structures.

Hello JSX

Without further ado, here's your first JSX application:

// The "render()" function will render JSX markup and 
// place the resulting content into a DOM node. The "React" 
// object isn't explicitly used here, but it's used 
// by the transpiled JSX source. 
import React from 'react'; 
import { render } from 'react-dom'; 
 
// Renders the JSX markup. Notice the XML syntax 
// mixed with JavaScript? This is replaced by the 
// transpiler before it reaches the browser. 
render( 
  (<p>Hello, <strong>JSX</strong></p>), 
  document.getElementById('app') 
); 

Pretty simple, right? Let's walk through what's happening here. First, we need to import the relevant bits. The render() function is what really matters in this example, as it takes JSX as the first argument and renders it to the DOM node passed as the second argument.

Note

The parentheses surrounding the JSX markup aren't strictly necessary. However, this is a React convention, and it helps us to avoid confusing markup constructs with JavaScript constructs.

The actual JSX content in this example fits on one line, and it simply renders a paragraph with some bold text inside. There's nothing fancy going on here, so we could have just inserted this markup into the DOM directly as a plain string. However, there's a lot more to JSX than what's shown here. The aim of this example was to show the basic steps involved in getting JSX rendered onto the page. Now, let's talk a little bit about declarative UI structure.

Note

JSX is transpiled into JavaScript statements; browsers have no idea what JSX is. I would highly recommend downloading the companion code for this book from https://github.com/PacktPublishing/React-and-React-Native, and running it as you read along. Everything transpiles automatically for you; you just need to follow the simple installation steps.

Declarative UI structure

Before we continue to plow forward with our code examples, let's take a moment to reflect on our hello world example. The JSX content was short and simple. It was also declarative, because it described what to render, not how to render it. Specifically, by looking at the JSX, you can see that this component will render a paragraph, and some bold text within it. If this were done imperatively, there would probably be some more steps involved, and they would probably need to be performed in a specific order.

So, the example we just implemented should give you a feel for what declarative React is all about. As we move forward in this chapter and throughout the book, the JSX markup will grow more elaborate. However, it's always going to describe what is in the user interface. Let's move on.