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