1. 程式人生 > >Fullstack React: What the heck is JSX?

Fullstack React: What the heck is JSX?

 

Hey Friend, it's Nate from Fullstack React.

Chances are you, if you've ever looked at a React component you've seen JavaScript that looks like this:

 
class HelloWorld extends React.Component {
  render() {
    return (
      <h1 className='large'>Hello World</h1>
    );
  }
}

What is that stuff that looks like HTML or XML? That's called JSX and it stands for JavaScript eXtension. It might seem weird to have XML tags in your JavaScript, but it turns out to be super useful. By the end of this email, you'll have a solid understanding of what JSX is, and how we'll use it to build powerful React apps.

All of our React components have a render function that specifies what the HTML output of our React component will be. JSX is a "language extension" that allows us to write JavaScript that looks like HTML.

Let me be clear: when you write JSX, it's really just calling a JavaScript function under the hood.

To see what this means, imagine we had a React component that renders an h1HTML tag. JSX allows us to declare an element in a manner that closely resembles HTML.

For instance, let's see a HelloWorld component that shows a message to the user. Without using JSX, we could write this component like the following:

 
class HelloWorld extends React.Component {
  render() {
    return (
      React.createElement(
        'h1',
        {className: 'large'},
        'Hello World'
      )
    );
  }
}

It can become cumbersome creating HTML using the function of React.createElement() everywhere, both specifying the attributes of a tag as well as defining child elements, especially when our component output grows in complexity. For example:

 
// Gross anti-example
// we don't actually write React code
// this way:
class HelloWorld extends React.Component {
  render() {
    return (
      React.createElement(
        'div',
        {className: 'container'},
        React.createElement(
          'span', { className: 'title' },
          React.createElement(
            'H3', { className: 'large' }, 'Hello world'
          )
        )
      )
    );
  }
}

The same output from above using JSX, more succinctly reads as the following:

 
class HelloWorld extends React.Component {
  render() {
    return (
     <div className='container'>
        <span className='title'>
          <h3 className='large'>Hello world</h3>
        </span>
     </div>
    );
  }
}

Using JSX, the component is easier to understand because it looks like HTML (although is not, as we'll look at in a minute).

While JSX looks like HTML, it's actually a succinct method of calling React.createElement().

React.createElement() is, essentially, the function which will cause the HTML to be rendered in our browser.

Why JSX?

As JSX is just JavaScript, we can execute JavaScript inside our JSX. We can execute arbitrary JavaScript inline with our code using the {} curly-brace syntax. For instance, we can add two numbers together inside our component:

 
<h1>{
1 + 1 }</h1>

Although we won't often use a hardcoded math operation in our templates, we can do interesting things with the full-power to execute JavaScript in our templates.

Although we won't often use a simple math operation in our templates, having the full capabilities of JavaScript let's us write concise, powerful templates.

For example, if we have an array of users in an admin screen, we might want to list the number of users and map over them in a table:

 
// assume we have this `users` object:
let users = [
  {name: 'Ari', email: '[email protected]'},
  {name: 'Nate', email:
'[email protected]'}
];

And then this JSX template:

 
<div>
  <h4>{ users.length }
users</h4>
  <table>
    <thead><tr><th>Name</th><th>Email</th></tr></thead>
    <tbody>
      {users.map(user => (
        <tr><td>{user.name}</td><td>{user.email}</td></tr>
      ))}
    </tbody>
  </table>
</div>

Displaying our users by iterating over an array

As JSX compiles to JavaScript we can use the .map operator on an array and then render that list of users into our template.

How to use it

In order to use JSX, we pass our JavaScript code through a "pre-compiler" which translates it into "standard" JavaScript that can be read by all browsers.

Typically, compiling JSX is done by using a tool called babel. When you use create-react-app babel is setup for you automatically. We talk about using create-react-app at length in the book, so check it out.

Perhaps you've heard that

What is the Virtual DOM anyway?

The Virtual DOM is a tree of JavaScript objects that represents the actual DOM.

One of the interesting reasons to use the Virtual DOM is the API it gives us. When using the Virtual DOM we code as if we're recreating the entire DOM on every update.

This idea of re-creating the entire DOM results in an easy-to-comprehend development model: instead keeping track of all DOM state changes in our head (and in our code), we simply return the DOM we wish to see.

React takes care of the transformation (from the old DOM, to the desired DOM) behind the scenes!

This idea of re-creating the Virtual DOM every update might sound like a bad idea: isn't it going to be slow? But, in fact, React's Virtual DOM implementation comes with important performance optimizations that make it very fast.

The Virtual DOM will:

  • use efficient diffing algorithms, in order to know what changed
  • update subtrees of the DOM simultaneously
  • batch updates to the DOM

All of this results in an easy-to-use and optimized way to build web apps.

The term "Virtual DOM" might seem a bit scary, but really what we're doing is building a tree of JavaScript objects that look like a trimmed down version of the real DOM. (Essentially we're creating a tree of ReactElement objects.)

Hope this clears it up!

Cheers!

Nate

P.S. If you want to learn how to use JSX within the context of a project, grab a copy of the Fullstack React book - in there we teach you how to use not only JSX, but data architecture, routing and everything you need to build complete apps.

 

Fullstack.io 3310 19th St. San Francisco, California 94110 United States (415) 729-4431

Fullstack.io
3310 19th St.
San Francisco, California 94110
United States

 

If you no longer wish to receive our emails, click the link below:
 Unsubscribe