Understanding JSX
You might have noticed this weird syntax in your App.js
file:
const element = <h1>Hello, world!</h1>;
This is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.
JSX produces React “elements”. We will explore rendering them to the DOM in the next section. Below, you can find the basics of JSX necessary to get you started.
At first, this syntax might look scary, but don't worry! It's simply a syntax extension of JavaScript and it's recommended to use it with React to describe what the UI should look like. It may remind you of a template language, but it comes with the full power of JavaScript.
In the end, it gets transpiled to JavaScript. The following two examples are identical:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
When you have more complex objects, with embedded HTML tags, you really appreciate JSX. For example, this is a valid JSX expression:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you <i>here</i>.</h2>
</div>
);
If you type this in regular JavaScript, the equivalent would be:
const element = React.createElement(
'div',
null,
React.createElement(
'h1',
null,
'Hello!'
),
React.createElement(
'h2',
null,
'Good to see you ',
React.createElement(
'i',
null,
'here'
),
'.'
)
);
Why Use JSX?​
React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.
Using JavaScript with JSX components​
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 also do conditionals:
function Component() {
return (
<div>
{messages.length > 0 &&
<h2>
You have {messages.length} unread messages.
</h2>
}
</div>
);
}
Or even loops:
function Component() {
return (
<ul>
{messages.map((message) =>
<li>{message}</li>
)}
</ul>
);
}