Chapter 3. Introduction to JSX

 

This chapter covers

  • Understanding JSX and its benefits
  • Setting up JSX transpilers with Babel
  • Being aware of React and JSX gotchas

Welcome to JSX! It’s one of the greatest things about React, in my opinion—and one of the most controversial subjects related to React in the minds of a few developers I spoke with (who, not surprisingly, haven’t yet built anything large in React).

Thus far, we’ve covered how to create elements and components so that you can use custom elements and better organize your UIs. You used JavaScript to create React elements, instead of working with HTML. But there’s a problem. Look at this code, and see if you can tell what’s happening:

render() {
  return React.createElement(
    'div',
    { style: this.styles },
    React.createElement(
      'p',
      null,
      React.createElement(
        reactRouter.Link,
        { to: this.props.returnTo },
        'Back'
      )
    ),
    this.props.children
  );
}

Were you able to tell that there are three elements, that they’re nested, and that the code uses a component from React Router? How readable is this code, compared to standard HTML? Do you think this code is eloquent? The React team agrees that reading (and typing, for that matter) a bunch of React.createElement() statements isn’t fun. JSX is the solution to this problem.

3.1. What is JSX, and what are its benefits?

3.2. Understanding JSX

3.3. Setting up a JSX transpiler with Babel

3.4. React and JSX gotchas

3.5. Quiz

3.6. Summary

3.7. Quiz answers

sitemap