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 ofclassName
. 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()
?