About
JSX is a Javascript HTML Like language that compiles to Javascript React API.
The first motivation of JSX is that reading and writing React elements, are easier.
Compilation
It permits to:
- write JSX elements
- that compile to React Elements (ie createElement).
Babel transpile (ie convert) JSX down to Javascript with React.createElement() calls. 1)
Example that you can run on the Babel online compiler playground
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
where: What is a React Element?
Pro / Cons
Pro: JSX:
- is easier to read
- can be used as a template because it can embedded javascript_expression
- Prevents Injection Attacks
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
Cons:
- It needs to be compiled
Syntax
Multiple line
Multiple JSX lines should be wrap in parentheses to avoid automatic semicolon insertion
Expression
Because Jsx is an expression, you can:
- use JSX inside if statements
- use JSX inside for loops,
- assign it to variables,
- accept it as arguments,
Loop / Concatenate
For Loop
- With a For loop, you feed an array that you put inside the JSX return expression
const items = []
for (const [index, value] of elements.entries()) {
items.push(<input value={value} label={index} key={index} />)
}
return (
<div>
{items}
</div>
);
Map Loop
- from an array
return (
<div>
{elements.map((value, index) => {
return <input value={value} label={index} key={index} />
})}
</div>
);
- from an object, you need to iterate over the keys with Object.keys function
<div>
{Object.keys(elementsObject).map((key) => {
return <input key={key} type="text" name={key} value={elementsObject[key]}/>
})}
</div>
Return it from functions
function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>;
}
return <h1>Hello, Stranger.</h1>;
}
Javascript expression
Any valid JavaScript expression can be written inside curly braces in JSX
<ReactElementTagName>
Hello, world!
<ChildReactElement/>
{ console.log("Javascript code is between {}") }
</ReactElementTagName>;
where:
Unicode
- Espace: {“\u00A0”}
Component Attribute
All Jsx attribute have a camelCase name in order to make a difference with html attribute:
- class becomes className
- tabindex becomes tabIndex
You should either use:
- quotes (for string values)
- or curly braces (for javascript_expressions),
but not both in the same attribute.
const element = <div tabIndex="0"></div>;
const element = <img src={user.avatarUrl}></img>;
Typescript
You declare the type with the JSX.Element
let inputElements: JSX.Element;