React - JSX

About

JSX is an React expression that compiles to the React - Component (User-defined Element) function creating a Component.

The first motivation of JSX is that it's easier to read.

Pro

JSX:

const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;

Compilation

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

Example that you can run on the Babel online compiler playground

This JSX Script

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

Becomes this Javascript

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

where: React - Component (User-defined Element)

Syntax

Multiple line

Multiple JSX lines should be wrap in parentheses to avoid automatic semicolon insertion

Jsx Expression

Because Jsx is an expression, you can:

  • use JSX inside if statements
  • use JSX inside for loops,
  • assign it to variables,
  • accept it as arguments,

Loop

  • With a For loop, you feed an array that you put inside the JSX return expression
............
const items = []
for (const [index, value] of elements.entries()) {
  items.push(<input value={value} label={index} />)
}

return (
<div>
    {items}
</div>
);
....
return (
<div>
    {elements.map((value, index) => {
        return <input value={value} label={index} />
    })}
</div>
);
....

Return it from functions

function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}

Javascript expression

Any valid JavaScript expression can be written inside curly braces in JSX

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

where:

Unicode

  • Espace: {“\u00A0”}

Component Attribute

All Jsx attribute have a camelCase name in order to make a difference with html attribute:

  • class becomes className
  • tabindex becomes tabIndex

You should either use:

but not both in the same attribute.

const element = <div tabIndex="0"></div>;
const element = <img src={user.avatarUrl}></img>;

Typescript

You declare the type with the JSX.Element

let inputElements: JSX.Element;

Execution

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.
<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
<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 <note tip> 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.</note>
<div id="root">
</div>
<script type="text/babel">
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
</script>

Documentation / Reference


Powered by ComboStrap