Forward Advance Learning

Introducing JSX

JSX is a JavaScript transpiler that extends JavaScript with additional features. JSX is JavaScript with XML, and it lets you embed XML templates right into your JavaScript.

For example, instead of writing this:

var cats = React.createElement(
"p",
null,
"Cats"
);

We can write this:

const cats = <p>Cats</p>;

Stateless Components

A simple component now looks like this:

const App = () =>
<div className="app">
<h1>My App</h1>
</div>

Embedding JavaScript

To insert JavaScript into an XML section of a JSX file, we use the curly braces, like so:

<button onClick={props.saveEveryone}>Save The World</button>

Loops

Say we have a list of cats:

const cats = [
{id: 1, name: "Sherlock"},
{id: 2, name: "Watson"}
]

We can map them to DOM nodes like so:

const Cats = (props) =>
<ul>
{
props.cats.map((cat) =>
<li id={cat.id}>
{cat.name}
</li>
)
}
</ul>

Props

If we write a component like this, our props become simple attributes of the html:

const App = () => {
let cat = {name: "Fluffy"};
return <Cat name={cat} />
}

We can then run this like this:

ReactDOM.render(
<App cat="miffy"></App>,
document.getElementById('app')
)

Exercise

Try out some JSX at the Babel repl here. Try to make an anchor with an h1 inside of it. Add an href attribute. Check what it compiles to. Try to add an onClick that calls a function.

Further Exercise

Try to make a JSX Hello World using a simple stateless component.

For bonus points, add a button with an onClick.

For hyperbonus points (yes, that's a thing), try to add an unordered list of catNames.

Work in the Pen below.

See the Pen React JSX Exercise by Nicholas Johnson (@superluminary) on CodePen.