About JSX
- “HTML” that you can write in JavaScript
 
JSX
JSX is an XML-like syntax extension to ECMAScript without any defined semantics.
— JSX spec
- has to be transpiled to JavaScript
 - not coupled to React!
 - other implementations: vue, preact, inferno, stencil, marko, etc…
 
Examples
- examples of JSX and what it transpiles to under the hood
 
Simple
- elements become calls to 
React.createElement() - first argument: type of element
 - third argument: the subtree (aka. children)
 
import React from 'react'
export default <p>Hello world!</p>
export const transpiledTo = React.createElement('p', {}, 'Hello world!')Hello world!
Props
- second argument: attributes (aka. props) as key-value pairs
 
import React from 'react'
export default <a href="https://reactjs.org/">React</a>
export const transpiledTo = React.createElement(
  'a',
  { href: 'https://reactjs.org/' },
  'React',
)Prop Types
- props can be of any type, not just strings
 
import React from 'react'
export default (
  <button type="button" onClick={() => alert('clicked')} tabIndex={-1}>
    <i>the button</i>
  </button>
)
export const transpiledTo = React.createElement(
  'button',
  { type: 'button', onClick: () => alert('clicked'), tabIndex: -1 },
  // note the nested `createElement` call
  React.createElement('i', {}, 'the button'),
)Spread Props
- objects can be spread on elements
 - applies all keys in the object as props
 
import React from 'react'
const propsToSpread = {
  onClick: () => alert(`please don't click me`),
}
export default (
  <button type="button" {...propsToSpread}>
    click me
  </button>
)
export const transpiledTo = React.createElement(
  'button',
  { type: 'button', ...propsToSpread },
  'click me',
)Interpolate
- values can be interpolated using 
{value} - usually renders as 
String(value) true,false,undefined,nullnever render; allows for short-circuit logic<></>is a fragment; allows for rendering multiple elements where one is expected
import React from 'react'
const hi = 'hi'
const canYouSeeMe = false
export default (
  <>
    string: {hi} <br />
    number: {42} <br />
    boolean: {true} {false} <br />
    short-circuit: {canYouSeeMe && <p>sure you can</p>} <br />
    nullish: {undefined} {null} <br />
  </>
)string: hi 
number: 42
boolean:
short-circuit:
nullish:
number: 42
boolean:
short-circuit:
nullish:
Repeat
- use 
array.map()to “loop” over values - use the special 
keyprop to distinguish elements in the array 
import React from 'react'
const fruits = ['apple', 'orange', 'strawberry']
export default (
  <ul>
    {fruits.map((fruit) => (
      <li key={fruit}>{fruit}</li>
    ))}
  </ul>
)- apple
 - orange
 - strawberry