React JSX

JSX stands for JavaScript XML and it allows us to write HTML directly within React. This makes it easier to create and manage HTML structures within React applications.



Coding with JSX

JSX allows us to write HTML elements directly in JavaScript and place them in the DOM without using createElement() and/or appendChild() methods. JSX converts HTML tags into React elements. While using JSX is not mandatory, it simplifies writing React applications.


Here are two examples: one with JSX and one without.

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 converted into regular JavaScript at runtime.

Using JSX

JS


Without JSX

JS




Expressions in JSX

With JSX, you can write expressions inside curly braces {}. These expressions can be React variables, properties, or any valid JavaScript expressions. JSX will execute the expression and return the result.

Execute the expression 5 + 5 EXAMPLE

JS



Inserting a Large Block of HTML

To write HTML over multiple lines, enclose the HTML code within parentheses.

Create a list with three items EXAMPLE

JS




One Top Level Element

The HTML code must be wrapped in a single top-level element. If you need to write two paragraphs, place them inside a parent element, such as a <div>.

Wrap two paragraphs inside a <div> element EXAMPLE

JS


JSX will throw an error if the HTML is not correctly structured or missing a parent element. Alternatively, you can use a “fragment” which prevents adding unnecessary nodes to the DOM.

A fragment looks like an empty HTML tag: <></>.

Wrap two paragraphs inside a fragment EXAMPLE

JS




Elements Must Be Closed

JSX follows XML rules, so HTML elements must be properly closed.

Close empty elements with a self-closing tag EXAMPLE

JS

JSX will throw an error if the HTML elements are not properly closed.




Attribute class = className

The class attribute is commonly used in HTML. However, since the class keyword is reserved in JavaScript, JSX uses className instead. When JSX is rendered, className attributes are converted to class attributes.

Using className instead of class in JSX EXAMPLE

JS




Conditions – if Statements

React supports if statements but not inside JSX. To use conditional statements in JSX, place the if statements outside the JSX or use a ternary expression.


Option 1: Write if statements outside JSX:

Write “Hello” if x is less than 10, otherwise “Goodbye” EXAMPLE

JS


Option 2: Use ternary expressions:

Write “Hello” if x is less than 10, otherwise “Goodbye” EXAMPLE

When embedding a JavaScript expression in JSX, remember to wrap the JavaScript with curly braces {}.

JS