JSX in Depth

JSX is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React.

Why JSX?

You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.

It's more familiar for casual developers such as designers.

XML has the benefit of balanced opening and closing tags. This helps make large trees easier to read than function calls or object literals.

It doesn't alter the semantics of JavaScript.

HTML Tags vs. React Components

React can either render HTML tags (strings) or React components (classes).

To render an HTML tag, just use lower-case tag names in JSX:

var myDivElement = <div className="foo" />;
ReactDOM.render(myDivElement, document.getElementById('example'));

To render a React Component, just create a local variable that starts with an upper-case letter:

var MyComponent = React.createClass({/*...*/});
var myElement = <MyComponent someProperty={true} />;
ReactDOM.render(myElement, document.getElementById('example'));

React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags.

Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className and htmlFor, respectively.

The Transform

React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments that are passed to React.createElement.

var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = React.createElement(Nav, {color:"blue"});

Notice that in order to use <Nav />, the Nav variable must be in scope.

JSX also allows specifying children using XML syntax:

var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = React.createElement(
  Nav,
  {color:"blue"},
  React.createElement(Profile, null, "click")
);

JSX will infer the class's displayName from the variable assignment when the displayName is undefined:

// Input (JSX):
var Nav = React.createClass({ });
// Output (JS):
var Nav = React.createClass({displayName: "Nav", });

Use the Babel REPL to try out JSX and see how it desugars into native JavaScript, and the HTML to JSX converter to convert your existing HTML to JSX.

If you want to use JSX, the Getting Started guide shows how to set up compilation.

The JSX expression always evaluates to a ReactElement. The actual implementation details may vary. An optimized mode could inline the ReactElement as an object literal to bypass the validation code in React.createElement.

Namespaced Components

If you are building a component that has many children, like a form, you might end up with something with a lot of variable declarations:

// Awkward block of variable declarations
var Form = MyFormComponent;
var FormRow = Form.Row;
var FormLabel = Form.Label;
var FormInput = Form.Input;

var App = (
  <Form>
    <FormRow>
      <FormLabel />
      <FormInput />
    </FormRow>
  </Form>
);

To make it simpler and easier, namespaced components let you use one component that has other components as attributes:

var Form = MyFormComponent;

var App = (
  <Form>
    <Form.Row>
      <Form.Label />
      <Form.Input />
    </Form.Row>
  </Form>
);

To do this, you just need to create your "sub-components" as attributes of the main component:

var MyFormComponent = React.createClass({ ... });

MyFormComponent.Row = React.createClass({ ... });
MyFormComponent.Label = React.createClass({ ... });
MyFormComponent.Input = React.createClass({ ... });

JSX will handle this properly when compiling your code.

var App = (
  React.createElement(Form, null,
    React.createElement(Form.Row, null,
      React.createElement(Form.Label, null),
      React.createElement(Form.Input, null)
    )
  )
);

This feature is available in v0.11 and above.

JavaScript Expressions

Attribute Expressions

To use a JavaScript expression as an attribute value, wrap the expression in a pair of curly braces ({}) instead of quotes ("").

// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = React.createElement(
  Person,
  {name: window.isLoggedIn ? window.name : ''}
);

Boolean Attributes

Omitting the value of an attribute causes JSX to treat it as true. To pass false an attribute expression must be used. This often comes up when using HTML form elements, with attributes like disabled, required, checked and readOnly.

// These two are equivalent in JSX for disabling a button
<input type="button" disabled />;
<input type="button" disabled={true} />;

// And these two are equivalent in JSX for not disabling a button
<input type="button" />;
<input type="button" disabled={false} />;

Child Expressions

Likewise, JavaScript expressions may be used to express children:

// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = React.createElement(
  Container,
  null,
  window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
);

Comments

It's easy to add comments within your JSX; they're just JS expressions. You just need to be careful to put {} around the comments when you are within the children section of a tag.

var content = (
  <Nav>
    {/* child comment, put {} around */}
    <Person
      /* multi
         line
         comment */
      name={window.isLoggedIn ? window.name : ''} // end of line comment
    />
  </Nav>
);

NOTE:

JSX is similar to HTML, but not exactly the same. See JSX gotchas for some key differences.

doc_React
2016-06-23 03:32:04
Comments
Leave a Comment

Please login to continue.