Introduction to JSX
# 01. Introduction to JSX
# What is JSX?
const element = <h1>Hello, world!</h1>;
A syntax that describes UI in a template-like manner. It is syntactic sugar for JS and is essentially JS. You can use variables, expressions, functions, etc. within it.
# Why Use JSX?
It co-locates markup with logic in loosely coupled units called "components" to achieve separation of concerns (opens new window).
React does not require using JSX, but having JSX alongside the UI in JavaScript code provides visual assistance.
# Embedding Expressions in JSX
const element = <h1>Hello, {2+2}</h1>;
You can put any valid JavaScript expression (opens new window) inside the curly braces in JSX.
# JSX is an Expression Too
After compilation, JSX expressions are converted to regular JavaScript function calls and evaluate to JavaScript objects.
You can treat JSX as an object -- assign it to variables, pass it as arguments to functions, return JSX, etc.
# JSX Specific Attributes
You may use quotes to specify string literals as attributes:
const element = <div tabIndex="0"></div>;
Attribute names in JSX use camelCase. For example,
tabIndexin the example above.
You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <img src={user.avatarUrl}></img>;
# Specifying Children with JSX
JSX tags may contain children:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
2
3
4
5
6
# JSX Prevents Injection Attacks
By default, React DOM escapes (opens new window) any values embedded in JSX before rendering them. It ensures that you can never inject anything that's not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) (opens new window) attacks.
# JSX Represents Objects
Babel compiles JSX down to React.createElement() function calls.
These two examples are identical:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1', // tag name
{className: 'greeting'}, // attributes object
'Hello, world!' // content
);
2
3
4
5
6
7
8
9
10
11