React - JSX

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

Component are created generally from a JSX expression that compiles to the createElement function.

JSX is a style of the template element that produces React Component.

Advertising

3 - JSX compilation

Babel transpile (ie convert) JSX down to Javascript with React.createElement() calls.

Example:

This JSX Script

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

Becomes this Javascript

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

where: createElement

4 - Syntax

example.jsx
<ReactElementTagName>
   Hello, world! 
   <ChildReactElement/>
   { console.log("Javascript code is between {}") } 
</ReactElementTagName>;

where:

5 - Example

5.1 - Browser

Normally, you will work in Node with a framework that will do the babel transpilling for you in the background.

but for a demo purpose and to understand how it works, this is how you set up a browser to render JSX

  • Library: Next to the React and ReactDom library, you need to add the Babel library.
index.html
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/babel.min.js"></script>
  • Inside your HTML page, The script that Babel will transpile must be tagged with the type text/babel
index.html
<script type="text/babel">
    function formatName(user) {
      return user.firstName + ' ' + user.lastName;
    }
 
    const user = {
      firstName: 'Nicolas',
      lastName: 'GERARD'
    };
 
    //  wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
    // http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi
    const element = (
      <h1>
        Hello, {formatName(user)}!
      </h1>
   );
</script>
  • The Root element where the React component will render It's called the “root” DOM node because it's the root of the React DOM Tree and React will render all its element inside it.
index.html
<div id="root">
</div>
index.html
<script type="text/babel">
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
</script>

Advertising

6 - Documentation / Reference

web/javascript/react/jsx.txt · Last modified: 2019/06/21 14:37 by gerardnico