React prefers developing with JSX files that loosely couples HTML and JS in the same file.
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2
, user.firstName
, or formatName(user)
are all valid JavaScript expressions.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
You can use JSX inside of if
statements and for
loops, assign it to variables, accept it as arguments, and return it from functions:
function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>;
}
return <h1>Hello, Stranger.</h1>;
}
Specifying Attributes with JSX. You may use quotes to specify string literals as attributes:
const element = <a href="https://www.reactjs.org"> link </a>;
You may also use curly braces to embed a JavaScript expression in an attribute. Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute.
const element = <img src={user.avatarUrl}></img>;
JSX tags may contain children:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
JSX Prevents Injection Attacks. It is safe to embed user input in JSX:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
By default, React DOM escapes any values embedded in JSX before rendering them. Thus 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) attacks.
JSX Represents Objects
Babel compiles JSX down to React.createElement()
calls. These two examples are identical:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
React.createElement()
performs a few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
}
These objects are called “React elements”. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
We recommend using the “Babel” language definition for your editor of choice so that both ES6 and JSX code is properly highlighted.
We will explore rendering React elements to the DOM in the next section.