JSX

Download reactjs eBook

Remarks

JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

Just like XML, JSX tags have a tag name, attributes, and children. If an attribute value is enclosed in quotes, the value is a string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression.

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function.

So, the following JSX code:

class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

ReactDOM.render(<HelloMessage name="Kalo" />, mountNode);

Compiles down to the following JavaScript code:

class HelloMessage extends React.Component {
  render() {
    return React.createElement(
      "div",
      null,
      "Hello ",
      this.props.name
    );
  }
}

ReactDOM.render(React.createElement(HelloMessage, { name: "Kalo" }), mountNode);

In conclusion, note that the following line in JSX is neither a string nor HTML:

const element = <h1>Hello, world!</h1>;

It is called JSX, and it is a syntax extension to JavaScript. JSX may remind you of a template language, but it comes with the full power of JavaScript.

The React team says in their docs that they recommend using it to describe what the UI should look like.

Related Examples

Stats

63 Contributors: 2
Friday, March 3, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook