class
vs className
class
is a reserved word in JS. You can't use class
in JSX, use className
instead:
<h1 className="big">Hey</h1>
Self-closing tags in JSX
<br /> // Fine in JSX
<br> // NOT fine in JSX
{}
Curly braces in JSX
Text inside {}
are treated like regular JavaScript instead of JSX. In the example below, ReactDOM.render()
will display a 5 instead of 2 + 3.
ReactDOM.render(
<h1>2 + 3 = {2 + 3}</h1>, // 2 + 3 = 5 -- {2 + 3} is treated like JS
document.getElementById('app')
);
const theBestString = 'tralalalala i am da best';
ReactDOM.render(
<h1>{theBestString}</h1>,
document.getElementById('app')
);
Variable Attributes in JSX
It's common to use variables to set attributes:
const sideLength = "200px"; // ←─
const panda = (
<img
src="images/panda.jpg"
alt="panda"
height={sideLength} // ←─
width={sideLength} /> // ←─
);
Object properties are also often used to set attributes:
const pics = {
panda: "http://bit.ly/1Tqltv5",
owl: "http://bit.ly/1XGtkM3",
owlCat: "http://bit.ly/1Upbczi"
};
const panda = (
<img
src={pics.panda} // ←─
alt="Lazy Panda" />
);
const owl = (
<img
src={pics.owl} // ←─
alt="Unimpressed Owl" />
);
const owlCat = (
<img
src={pics.owlCat} // ←─
alt="Ghastly Abomination" />
);
Handling Events
Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
For example, the HTML:
<button onclick="activateLasers()">Activate Lasers</button>
is slightly different in React:
<button onClick={activateLasers}>Activate Lasers</button>
An event listener attribute's name should be the word on
plus the type of event you're listening for. Here's a list of valid even names.
An event listener's value should be a function. The above example would only work if activateLasers
were a valid function that had been defined elsewhere:
function activateLasers () {
console.log("Firing the lasers!");
}
<button onClick={activateLasers}>Activate Lasers</button>
JSX Conditionals: If Statements That Work
function coinToss() {
// This function will randomly return either 'heads' or 'tails'.
return Math.random() < 0.5 ? 'heads' : 'tails';
}
const pics = {
kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'
};
let img;
if (coinToss() === 'heads') {
img = <img src={pics.kitty} />;
} else {
img = <img src={pics.doggy} />;
}
ReactDOM.render(img, document.getElementById('app'));
JSX Conditionals: If Statements That Don't Work!
(
<h1>
{
if (purchase.complete) { // You CAN'T inject a JS if statement into JSX!
'Thank you for placing an order!'
}
}
</h1>
)
JSX Conditionals: Ternary Operator
function coinToss () {
// Randomly return either 'heads' or 'tails'.
return Math.random() < 0.5 ? 'heads' : 'tails';
}
const pics = {
kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'
};
const img = <img src={pics[coinToss() === 'heads' ? 'kitty' : 'doggy']} />;
ReactDOM.render(
img,
document.getElementById('app')
);
JSX Conditionals: &&
With &&
, both conditions have to be true, otherwise no action will take place.
// judgmental will be true half the time.
const judgmental = Math.random() < 0.5;
const favoriteFoods = (
<div>
<h1>My Favorite Foods</h1>
<ul>
<li>Sushi Burrito</li>
<li>Berry Pie</li>
{!judgmental && <li>Nutella & Peanut Butter Sandwich</li>}
<li>Grapefruit</li>
</ul>
</div>
);
ReactDOM.render(
favoriteFoods,
document.getElementById('app')
);
.map
in JSX
const people = ['Rowe', 'Prevost', 'Gare'];
const peopleLis = people.map(person =>
<li>{person}</li>
);
ReactDOM.render(<ul>{peopleLis}</ul>, document.getElementById('app'))
Start off with an array of people. .map()
is called on the array of people and .map()
returns a new array of <li>
.
{peopleLis}
will evaluate to an array because it's the returned value of .map()
<li>
Keys
Lists in JSX will need to include keys
, a JSX attribute.
<ul>
<li keys="li-01">Example01</li>
<li keys="li-02">Example02</li>
</ul>
Not all lists need to havekeys
. A list needskeys
if either of the following are true:
The list-items have _memory _from one render to the next. For instance, when a to-do list renders, each item must "remember" whether it was checked off. The items shouldn't get amnesia when they render.
A list's order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.
Assigning a unique key using .map()
const people = ['Rowe', 'Prevost', 'Gare'];
const peopleLis = people.map((person, i) =>
<li key={'person_' + i}>{person}</li>
);
ReactDOM.render(<ul>{peopleLis}</ul>, document.getElementById('app'))
React.createElement
Under the hood, React transforms JSX elements into the React.createElement()
method . Every JSX element is secretly a call to React.createElement()
.
The following JSX expression:
const h1 = <h1>Hello world!</h1>;
can be rewritten without JSX , like this:
const React.createElement(
"h1",
null,
"Hello, world!"
);
More on this topic here: https://facebook.github.io/react/docs/react-api.html