React JSX
React JSX
Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods.
You are not required to use JSX, but JSX makes it easier to write React applications.
Here are two examples. The first uses JSX and the second does not:
JSX:
root.render(myElement);
Run Example »
Example 2
Without JSX:
root.render(myElement);
Run Example »
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript
at runtime.
Expressions in JSX
Example
Run Example »
Example
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
Run Example »
So if you like to write two paragraphs, you must put them inside a parent element, like a div element.
Example
const myElement = (
<div>
<p>I am a paragraph.</p>
</div>
);
Run Example »
JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.
Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily adding
extra nodes to the DOM.
Example
const myElement = (
<>
<p>I am a paragraph.</p>
</>
);
Run Example »
JSX follows XML rules, and therefore HTML elements must be properly closed.
Example
Run Example »
The class attribute is a much used attribute in HTML, but since JSX is rendered as JavaScript, and
the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.
JSX solved this by using className instead. When JSX is rendered, it translates className attributes
into class attributes.
Example
Conditions - if statements
To be able to use conditional statements in JSX, you should put the if statements outside of the JSX,
or you could use a ternary expression instead:
Option 1:
Example
const x = 5;
if (x < 10) {
text = "Hello";
Run Example »
Option 2:
Example
const x = 5;
Run Example »
Note that in order to embed a JavaScript expression inside JSX, the JavaScript must be wrapped with
curly braces, {}.