Skip to content
hhh edited this page Jan 22, 2019 · 5 revisions

JSX Usage

TOC

Introduction

JSX is an extension to JavaScript which enables you to use XML-like syntax in JavaScript. For example:

const heading = <h1>This is JSX.</h1>;

It is usually nice to write UIs in JSX. However, it is optional. In fact, all the JSX code will be converted into normal JavaScript function calls. For instance,

const paragraph = <p class="para">JSX</p>;

will be transformed into something like this: (assuming the JSX factory function is HUI)

const paragraph = HUI("p", { class: "para" }, "JSX");

Syntax

As introduced at the beginning, JSX just brings an XML-like syntax sugar to JavaScript, so its syntax is JavaScript+XML in brief.

Extra syntax

  1. Any tag can be self-closed if it doesn't have child nodes.

    const emptyContainer = <div class="container" />;
    const appWithoutChildren = <App foo="bar" />;
  2. Expressions can be inserted by wrapping them with braces.

    const dynamicParagraph = <p>Time: {Date.now()}</p>;
    const appWithConfig = <App config={{ debug: true }} />;
    const inputWithListener = <input oninput={(event) => {
        handleInput(event);
    }} />;
  3. A tag name starting with an uppercase letter will be considered a custom identifier.

    import MyComponent from "MyComponent";
    const myComponent = <MyComponent />;
  4. An attribute whose value is omitted will be set to true. So,

    const input = <input autofocus />;

    is equal to

    const input = <input autofocus={true} />;

Transpile

JSX is just a syntax sugar and it can not be directly run in browsers like plain JavaScript, so you need to transpile your JSX code into plain JavaScript. There are many tools which can do this for you. Here are some examples:

Babel

Babel is a compiler for next generation JavaScript. It can also transform JSX syntax with a plugin.

  1. Install Babel.

  2. Install the JSX transformer:

    npm i -D @babel/plugin-transform-react-jsx
  3. Set your .babelrc like this:

    {
        // ...
        "plugins": [
            // ...
            [
                "@babel/plugin-transform-react-jsx",
                {
                    "pragma": "HUI",
                    "pragmaFrag": "HUI.Fragment"
                }
            ],
            // ...
        ],
        // ...
    }
  4. Use Babel to transform your code.

For more information about Babel, see babeljs.io.

TypeScript

TypeScript supports JSX out of the box.

  1. Install TypeScript compiler.

  2. Set your tsconfig.json like this:

    {
        // ...
        "compilerOptions": {
            // ...
            "jsx": "react",
            "jsxFactory": "HUI",
            // ...
        },
        // ...
    }
  3. Compile your TypeScript code.

For more information about TypeScript, see www.typescriptlang.org.

Clone this wiki locally