As we mentioned in the introduction of this chapter, JSX is an extension to JavaScript. It expands the syntax of the language to allow writing XML-like code in JavaScript.
In reality, JSX is only syntactic sugar; it is never executed as is at runtime. A build step is required to transform JSX code into JavaScript. The default choice for handling this transformation is Babel but as we'll see later, TypeScript can also take care of it for us.
Here's a basic example of JSX code:
const element = <h1>Hello, world!</h1>;
Here, we created a simple React element (we'll explain what those are in the next section).
JSX elements such as the preceding one actually get converted into calls like these: React.createElement(component, props, ...children), which are API calls used to create React elements.
Here's what the preceding code becomes once transpiled into JavaScript:
const element = React.createElement('h1', null, 'Hello, world!');
One goal of React with JSX is to keep state away from the DOM. If you think about it, what Angular and Vue.js do is introduce a fairly limited JavaScript-like syntax into HTML templates. React does the opposite; it uses HTML-like syntax in JavaScript code.
An important benefit of React's approach with JSX is that if you know JavaScript, then you know most of the syntax needed to write React applications. Getting better at React mostly means getting better at JavaScript. Obviously, this is an advantage compared to the framework-specific syntaxes that we learned about for Angular and Vue.js, which takes a bit of time to master.
Here's another JSX example taken from the official documentation:
class Hello extends React.Component { render() { return <div>Hello {this.props.toWhat}</div>; } } ReactDOM.render( <Hello toWhat="World" />, document.getElementById('root') );
And here's the transpiled version:
class Hello extends React.Component { render() { return React.createElement('div', null, "Hello",
this.props.toWhat); } } ReactDOM.render( React.createElement(Hello, {toWhat: 'World'}), document.getElementById('root') );
Don't worry about the class for now; we'll explore the different ways to create React components in the next section.
As you can guess from the preceding code, it is actually not mandatory to use JSX with React when writing components, but it is the default and recommended choice. The official documentation provides instructions on how to use React without JSX: https://reactjs.org/docs/react-without-jsx.html.
JSX makes the code of components more readable. Also, as stated in the official documentation, it allows React to show useful error messages.