React ๐ŸŽ„

Day 2: JSX 4 LYFE

People like to make hay about JSX.

Donโ€™t get your undies in a bunched. All it does is make these two lines equivalent:

// No-JSX
React.createElement("h1", {}, "Hello ๐ŸŽ„")

// YAAAAS!!!-JSX
<h1>Hello ๐ŸŽ„</h1>

How does HTML work in JavaScript?

Donโ€™t think of it like HTML, it isnโ€™t.

JSX is just a authoring nice-to-have. But itโ€™s not something that works in the browser. It must be transformed to React.createElement() calls before the browser can run it. Most apps use projects like Babel or TypeScript to handle that.

Why JSX?

JSX is optional but it has community consensus. Thereโ€™s a certain harmony to specโ€™ing React elements in a syntax similar to HTML.

Gotchas

JSX isnโ€™t all ๐Ÿฆ„s and ๐ŸŒˆs.

Lowercase attributes like class, onclick, autofocus, and tabindex become camelCased className, onClick, autoFocus, and tabIndex respectively.

They can also take any JavaScript expression.

This takes time to get used to. The examples below are identical.

HTML

<button
  type="button"
  autofocus
  class="some-button"
  onclick="alert('HTML!')"
>Hello ๐ŸŽ„</button>

JSX

<button
  type="button"
  autoFocus
  className="some-button"
  onClick={() => alert('JSX!')}
>Hello ๐ŸŽ„</button>

JS

React.createElement(
  'button',
  {
    type: 'button',
    autoFocus: true,
    className: 'some-button',
    onClick: () => alert('JS!'),
  },
  'Hello ๐ŸŽ„'
)

Tinker with it

Use the workspace below and play with the JSX.

  • Try using class instead of className. What error do you get?
  • Nest a couple elements inside of each other. Did they render as expected? How would you write the same using React.createElement()?
โ† Previous
Next โ†’

Learn other React stuff...