Using JSX via Babel

The creation of the React HelloMessage component and React <div> element node in the HTML page below was done using the React.createClass() and React.createElement() functions. This code should look familiar as it is identical to the HTML from the previous section. This HTML will run without errors in ES5 browsers.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://fb.me/react-15.2.0.js"></script>
        <script src="https://fb.me/react-dom-15.2.0.js"></script>
    </head>
<body>
    <div id="app"></div>
    <script>
        var HelloMessage = React.createClass({
            displayName: 'HelloMessage',
            render: function render() {
                return React.createElement('div',null,'Hello ',this.props.name);
            }
        });
        ReactDOM.render(React.createElement(HelloMessage,{ name: 'John' }), document.getElementById('app'));
    </script>
</body>
</html>

Optionally, by using JSX via Babel, it is possible to simplify the creation of React elements by abstracting the React.createElement() JavaScript function calls so they can be written in a more natural HTML-like style and syntax.

Instead of writing the following, which uses React.createElement():

return React.createElement('div',null,'Hello ',this.props.name);

Using JSX, you can write this:

return <div>Hello {this.props.name}</div>;

And then Babel will convert it back to the code which uses React.createElement() so it can be parsed by a JavaScript engine.

Loosely stated you can consider JSX a form of HTML that you can directly write in JavaScript that requires a transformation step, done by Babel, into ECMAScript 5 code that browsers can run.

More will be said about JSX in the JSX chapter. For now, just realize that JSX is an optional abstraction provided for your convenience when creating React elements and it won't run in ES5 browsers without first being transformed by Babel.

Transforming JSX via Babel in the Browser

Normally, Babel is setup to automatically process your JavaScript files during development using the Babel CLI tool (e.g., via something like webpack). However, it is possible to use Babel directly in the browser by way of a script include. As we are just getting started we'll avoid CLI tools or learning a module loader to focus on learning React. Note that you should never use this browser transformation in a production environment.

The Babel project unfortunately, as of Babel 6, no longer provides the script file needed (i.e., browser.js) to transform JSX code to ES5 code in the browser. Thus you will have to use an older version of Babel (i.e., 5.8.23) that provides the needed file (i.e., browser.js) for transforming JSX/ES* in the browser.

Using browser.js (Babel 5.8.23) to Transform JSX in the Browser

In the HTML file below the React code we have been working with to create the HelloMessage component has been updated to use JSX. The transformation of the code is occurring because we have included the browser.js Babel file and given the <script> element a type attribute of type="text/babel".

<!DOCTYPE html>
<html>
    <head>
        <script src="https://fb.me/react-15.2.0.js"></script>
        <script src="https://fb.me/react-dom-15.2.0.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
    </head>
<body>
    <div id="app"></div>
    <script type="text/babel">
        var HelloMessage = React.createClass({
            render: function() {
                return <div>Hello {this.props.name}</div>;
            }
        });

        ReactDOM.render(<HelloMessage name="John" />, document.getElementById('app'));
    </script>
</body>
</html>

While transforming JSX in the browser is convenient and easy to setup, it isn't ideal because the transformation cost is occurring at runtime. This will slow down your web pages and may cause memory issues. Therefore using browser.js is not a production solution.

You should be aware that the code examples used in this book via JSFiddle will be using the browser.js (Babel 5.8.23) to transform JSX into ES5 code. In other words, JSFiddle is pretty much doing what you see in the HTML file above when running React code.

Notes

  • The Babel tool is a subjective selection from the React team for transforming ES* code and JSX syntax to ES5 code. Learn more about Babel by reading the Babel handbook.
  • By using JSX:
    • Less technical people can still understand and modify the required parts. CSS developers and designers will find JSX more familiar than JavaScript alone.
    • You can leverage the full power of JavaScript in HTML and avoid learning or using a templating language. JSX is not a templating solution. It is a declarative syntax used to express a tree structure of UI components.
    • The compiler will find errors in your HTML you might otherwise miss.
    • JSX promotes the idea of inline styles. Which can be a good thing.
  • Beware of JSX Gotchas.
  • A JSX specification is currently being drafted. It can be used by anyone as an a XML-like syntax extension to ECMAScript without any defined semantics.

results matching ""

    No results matching ""